From e1114af8f5e5027e5dcb163e493a297699c888d0 Mon Sep 17 00:00:00 2001 From: grammarware Date: Sat, 16 May 2009 17:11:34 +0000 Subject: [PATCH] enforcing a renaming consistently git-svn-id: https://slps.svn.sourceforge.net/svnroot/slps@633 ab42f6e0-554d-0410-b580-99e487e6eeb2 --- topics/java/Makefile | 66 +- topics/java/jls1/Makefile | 32 +- topics/java/jls1/app.html | 875 - topics/java/jls1/doc.html | 9858 ----------- topics/java/jls1/impl.html | 239 + topics/java/jls1/read.html | 1912 +++ topics/java/jls2/Makefile | 28 +- topics/java/jls2/app.html | 399 - topics/java/jls2/doc.html | 9299 ---------- topics/java/jls2/impl.html | 239 + topics/java/jls2/read.html | 1912 +++ topics/java/jls3/Makefile | 28 +- topics/java/jls3/app.html | 541 - topics/java/jls3/doc.html | 13958 ---------------- topics/java/jls3/impl.html | 239 + topics/java/jls3/read.html | 1912 +++ .../java/lci/snapshot/architecture_large.pdf | Bin 37117 -> 38272 bytes .../java/lci/snapshot/architecture_small.pdf | Bin 10982 -> 11525 bytes 18 files changed, 6530 insertions(+), 35007 deletions(-) delete mode 100644 topics/java/jls1/app.html delete mode 100644 topics/java/jls1/doc.html create mode 100644 topics/java/jls1/impl.html create mode 100644 topics/java/jls1/read.html delete mode 100644 topics/java/jls2/app.html delete mode 100644 topics/java/jls2/doc.html create mode 100644 topics/java/jls2/impl.html create mode 100644 topics/java/jls2/read.html delete mode 100644 topics/java/jls3/app.html delete mode 100644 topics/java/jls3/doc.html create mode 100644 topics/java/jls3/impl.html create mode 100644 topics/java/jls3/read.html diff --git a/topics/java/Makefile b/topics/java/Makefile index c14cf5ba..439e0acc 100644 --- a/topics/java/Makefile +++ b/topics/java/Makefile @@ -13,39 +13,39 @@ test: cd jls1 ; make all cd jls2 ; make all cd jls3 ; make all - ../../shared/tools/gdts jls1/app1.bgf lci/snapshot/app1.bgf - ../../shared/tools/gdts jls2/app2.bgf lci/snapshot/app2.bgf - ../../shared/tools/gdts jls3/app3.bgf lci/snapshot/app3.bgf - ../../shared/tools/gdts jls1/doc1.bgf lci/snapshot/doc1.bgf - ../../shared/tools/gdts jls2/doc2.bgf lci/snapshot/doc2.bgf - ../../shared/tools/gdts jls3/doc3.bgf lci/snapshot/doc3.bgf + ../../shared/tools/gdts jls1/impl1.bgf lci/snapshot/impl1.bgf + ../../shared/tools/gdts jls2/impl2.bgf lci/snapshot/impl2.bgf + ../../shared/tools/gdts jls3/impl3.bgf lci/snapshot/impl3.bgf + ../../shared/tools/gdts jls1/read1.bgf lci/snapshot/read1.bgf + ../../shared/tools/gdts jls2/read2.bgf lci/snapshot/read2.bgf + ../../shared/tools/gdts jls3/read3.bgf lci/snapshot/read3.bgf rebuild: - curl -k http://java.sun.com/docs/books/jls/first_edition/html/19.doc.html > jls1/app.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/syntax.doc.html > jls2/app.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/syntax.html > jls3/app.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/4.doc.html >jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/6.doc.html >>jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/7.doc.html >>jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/8.doc.html >>jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/9.doc.html >>jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/10.doc.html >>jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/14.doc.html >>jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/first_edition/html/15.doc.html >>jls1/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html >jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html >>jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/packages.doc.html >>jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html >>jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html >>jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html >>jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html >>jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html >>jls2/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html >jls3/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/names.html >>jls3/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/packages.html >>jls3/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/classes.html >>jls3/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html >>jls3/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/arrays.html >>jls3/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/statements.html >>jls3/doc.html - curl -k http://java.sun.com/docs/books/jls/third_edition/html/expressions.html >>jls3/doc.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/19.read.html > jls1/impl.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/syntax.read.html > jls2/impl.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/syntax.html > jls3/impl.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/4.read.html >jls1/read.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/6.read.html >>jls1/read.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/7.read.html >>jls1/read.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/8.read.html >>jls1/read.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/9.read.html >>jls1/read.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/10.read.html >>jls1/read.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/14.read.html >>jls1/read.html + curl -k http://java.sun.com/reads/books/jls/first_edition/html/15.read.html >>jls1/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/typesValues.read.html >jls2/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/names.read.html >>jls2/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/packages.read.html >>jls2/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/classes.read.html >>jls2/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/interfaces.read.html >>jls2/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/arrays.read.html >>jls2/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/statements.read.html >>jls2/read.html + curl -k http://java.sun.com/reads/books/jls/second_edition/html/expressions.read.html >>jls2/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/typesValues.html >jls3/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/names.html >>jls3/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/packages.html >>jls3/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/classes.html >>jls3/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/interfaces.html >>jls3/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/arrays.html >>jls3/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/statements.html >>jls3/read.html + curl -k http://java.sun.com/reads/books/jls/third_edition/html/expressions.html >>jls3/read.html diff --git a/topics/java/jls1/Makefile b/topics/java/jls1/Makefile index d99943c1..42231fd8 100644 --- a/topics/java/jls1/Makefile +++ b/topics/java/jls1/Makefile @@ -1,27 +1,27 @@ all: - make app - make doc + make impl + make read make test debug: - python ../../extraction/html2bgf/getpre.py syntax.kw app.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html app1.bgf -v - python ../../extraction/html2bgf/getpre.py collect.kw doc.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html doc1.bgf -v + python ../../extraction/html2bgf/getpre.py syntax.kw impl.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html impl1.bgf -v + python ../../extraction/html2bgf/getpre.py collect.kw read.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html read1.bgf -v -app: - @echo "Extracting app1" > /dev/stderr - python ../../extraction/html2bgf/getpre.py syntax.kw app.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html app1.bgf +impl: + @echo "Extracting impl1" > /dev/stderr + python ../../extraction/html2bgf/getpre.py syntax.kw impl.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html impl1.bgf -doc: - @echo "Extracting doc1" > /dev/stderr - python ../../extraction/html2bgf/getpre.py collect.kw doc.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html doc1.bgf +read: + @echo "Extracting read1" > /dev/stderr + python ../../extraction/html2bgf/getpre.py collect.kw read.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html read1.bgf test: - ../../../shared/tools/checkxml bgf app1.bgf - ../../../shared/tools/checkxml bgf doc1.bgf + ../../../shared/tools/checkxml bgf impl1.bgf + ../../../shared/tools/checkxml bgf read1.bgf clean: rm -f *.bgf parse.html diff --git a/topics/java/jls1/app.html b/topics/java/jls1/app.html deleted file mode 100644 index 520875a5..00000000 --- a/topics/java/jls1/app.html +++ /dev/null @@ -1,875 +0,0 @@ - - - - -The Java Language Specification - LALR(1) Grammar - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

- - -

-CHAPTER - 19

- -

LALR(1) Grammar

-

- -This chapter presents a grammar for Java. The grammar has been mechanically -checked to insure that it is LALR(1). -

-The grammar for Java presented piecemeal in the preceding chapters is much better for exposition, but it cannot be parsed left-to-right with one token of lookahead because of certain syntactic peculiarities, some of them inherited from C and C++. These problems and the solutions adopted for the LALR(1) grammar are presented below, followed by the grammar itself.

- -

19.1 Grammatical Difficulties

- -There are five problems with the grammar presented in preceding chapters. -

-

19.1.1 Problem #1: Names Too Specific

- -Consider the two groups of productions: -

-and: -

-Now consider the partial input: -

class Problem1 { int m() { hayden.
-
-When the parser is considering the token hayden, with one-token lookahead to -symbol ".", it cannot yet tell whether hayden should be a PackageName that -qualifies a type name, as in: -

hayden.Dinosaur rex = new hayden.Dinosaur(2);
-
-or an AmbiguousName that qualifies a method name, as in: -

hayden.print("Dinosaur Rex!");
-
-Therefore, the productions shown above result in a grammar that is not LALR(1). -There are also other problems with drawing distinctions among different kinds of -names in the grammar. -

-The solution is to eliminate the nonterminals PackageName, TypeName, ExpressionName, MethodName, and AmbiguousName, replacing them all with a single nonterminal Name:

-

-A later stage of compiler analysis then sorts out the precise role of each name or -name qualifier. -

-For related reasons, these productions in §4.3:

-

-were changed to: -

-

19.1.2 Problem #2: Modifiers Too Specific

- -Consider the two groups of productions: -

-and: -

-Now consider the partial input: -

class Problem2 { public static int
-
-When the parser is considering the token static, with one-token lookahead to -symbol int-or, worse yet, considering the token public with lookahead to -static-it cannot yet tell whether this will be a field declaration such as: -

public static int maddie = 0;
-
-or a method declaration such as: -

public static int maddie(String art) { return art.length(); }
-
-Therefore, the parser cannot tell with only one-token lookahead whether static -(or, similarly, public) should be reduced to FieldModifier or MethodModifier. -Therefore, the productions shown above result in a grammar that is not LALR(1). -There are also other problems with drawing distinctions among different kinds of -modifiers in the grammar. -

-While not all contexts provoke the problem, the simplest solution is to combine all contexts in which such modifiers are used, eliminating all six of the nonterminals ClassModifiers (§8.1.2), FieldModifiers (§8.3.1), MethodModifiers (§8.4.3), ConstructorModifiers (§8.6.3), InterfaceModifiers (§9.1.2), and ConstantModifiers (§9.3) from the grammar, replacing them all with a single nonterminal Modifiers:

-

-A later stage of compiler analysis then sorts out the precise role of each modifier -and whether it is permitted in a given context. -

-

19.1.3 Problem #3: Field Declaration versus Method Declaration

- -Consider the two productions (shown after problem #2 has been corrected): -

-and: -

-where ResultType is defined as: -

-Now consider the partial input: -

class Problem3 { int julie
-
-Note that, in this simple example, no Modifiers are present. When the parser is -considering the token int, with one-token lookahead to symbol julie, it cannot -yet tell whether this will be a field declaration such as: -

int julie = 14;
-
-or a method declaration such as: -

int julie(String art) { return art.length(); }
-
-Therefore, after the parser reduces int to the nonterminal Type, it cannot tell with -only one-token lookahead whether Type should be further reduced to ResultType -(for a method declaration) or left alone (for a field declaration). Therefore, the -productions shown above result in a grammar that is not LALR(1). -

-The solution is to eliminate the ResultType production and to have separate alternatives for MethodHeader:

-

-This allows the parser to reduce int to Type and then leave it as is, delaying the decision as to whether a field declaration or method declaration is in progress.

- -

19.1.4 Problem #4: Array Type versus Array Access

- -Consider the productions (shown after problem #1 has been corrected): -

-and: -

-Now consider the partial input: -

class Problem4 { Problem4() { peter[
-
-When the parser is considering the token peter, with one-token lookahead to -symbol [, it cannot yet tell whether peter will be part of a type name, as in: -

peter[] team;
-
-or part of an array access, as in: -

peter[3] = 12;
-
-Therefore, after the parser reduces peter to the nonterminal Name, it cannot tell -with only one-token lookahead whether Name should be reduced ultimately to -Type (for an array type) or left alone (for an array access). Therefore, the productions -shown above result in a grammar that is not LALR(1). -

-The solution is to have separate alternatives for ArrayType:

-

-This allows the parser to reduce peter to Name and then leave it as is, delaying -the decision as to whether an array type or array access is in progress. -

-

19.1.5 Problem #5: Cast versus Parenthesized Expression

- -Consider the production: -

-Now consider the partial input: -

class Problem5 { Problem5() { super((matthew)
-
-When the parser is considering the token matthew, with one-token lookahead to -symbol ), it cannot yet tell whether (matthew) will be a parenthesized expression, -as in: -

super((matthew), 9);
-
-or a cast, as in: -

super((matthew)baz, 9);
-
-Therefore, after the parser reduces matthew to the nonterminal Name, it cannot -tell with only one-token lookahead whether Name should be further reduced to -PostfixExpression and ultimately to Expression (for a parenthesized expression) or -to ClassOrInterfaceType and then to ReferenceType (for a cast). Therefore, the -productions shown above result in a grammar that is not LALR(1). -

-The solution is to eliminate the use of the nonterminal ReferenceType in the definition of CastExpression, which requires some reworking of both alternatives to avoid other ambiguities:

-

-This allows the parser to reduce matthew to Expression and then leave it there, -delaying the decision as to whether a parenthesized expression or a cast is in -progress. Inappropriate variants such as: -

(int[])+3
-
-and: -

(matthew+1)baz
-
-must then be weeded out and rejected by a later stage of compiler analysis. -

-The remaining sections of this chapter constitute a LALR(1) grammar for Java syntax, in which the five problems described above have been solved.

- -

19.2 Productions from §2.3: The Syntactic Grammar

- -

19.3 Productions from §3: Lexical Structure

- -

19.4 Productions from §4: Types, Values, and Variables

- -

19.5 Productions from §6: Names

- -

19.6 Productions from §7: Packages

- -

19.7 Productions Used Only in the LALR(1) Grammar

- -

19.8 Productions from §8: Classes

- -

19.8.1 Productions from §8.1: Class Declaration

- -

19.8.2 Productions from §8.3: Field Declarations

- -

19.8.3 Productions from §8.4: Method Declarations

- -

19.8.4 Productions from §8.5: Static Initializers

- -

19.8.5 Productions from §8.6: Constructor Declarations

- -

19.9 Productions from §9: Interfaces

- -

19.9.1 Productions from §9.1: Interface Declarations

- -

19.10 Productions from §10: Arrays

- -

19.11 Productions from §14: Blocks and Statements

- -

19.12 Productions from §15: Expressions

- -

- - -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- \ No newline at end of file diff --git a/topics/java/jls1/doc.html b/topics/java/jls1/doc.html deleted file mode 100644 index f2920b8c..00000000 --- a/topics/java/jls1/doc.html +++ /dev/null @@ -1,9858 +0,0 @@ - - - - -The Java Language Specification - Types, Values, and Variables - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 4

- -

Types, Values, and Variables

-

- -Java is a strongly typed language, which means that every variable and every -expression has a type that is known at compile time. Types limit the values that a -variable (§4.5) can hold or that an expression can produce, limit the operations -supported on those values, and determine the meaning of the operations. Strong -typing helps detect errors at compile time. -

-The types of the Java language are divided into two categories: primitive types and reference types. The primitive types (§4.2) are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types (§4.3) are class types, interface types, and array types. There is also a special null type. An object (§4.3.1) in Java is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object (§4.3.2). String literals are represented by String objects (§4.3.3).

- -Types are the same (§4.3.4) if they have the same fully qualified names and are loaded by the same class loader. Names of types are used (§4.4) in declarations, in casts, in class instance creation expressions, in array creation expressions, and in instanceof operator expressions.

- -A variable (§4.5) is a storage location. A variable of a primitive type always holds a value of that exact type. A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T. A variable of an interface type can hold a null reference or a reference to any instance of any class that implements the interface. If T is a primitive type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of T"; if T is a reference type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of S" such that type S is assignable (§5.2) to type T. A variable of type Object can hold a null reference or a reference to any object, whether class instance or array.

- -

4.1 The Kinds of Types and Values

- -There are two kinds of types in Java: primitive types (§4.2) and reference types -(§4.3). There are, correspondingly, two kinds of data values that can be stored in -variables, passed as arguments, returned by methods, and operated on: primitive -values (§4.2) and reference values (§4.3). -

-There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the Java programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

- -

4.2 Primitive Types and Values

- -A primitive type is predefined by the Java language and named by its reserved -keyword (§3.9): -

-Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable.

- -The numeric types are the integral types and the floating-point types.

- -The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.

- -The floating-point types are float, whose values are 32-bit IEEE 754 floating-point numbers, and double, whose values are 64-bit IEEE 754 floating-point numbers.

- -The boolean type has exactly two values: true and false.

- -

4.2.1 Integral Types and Values

- -The values of the integral types are integers in the following ranges: -

-

4.2.2 Integer Operations

- -Java provides a number of operators that act on integral values: -

-Other useful constructors, methods, and constants are predefined in the classes -Integer (§20.7), Long (§20.8), and Character (§20.5). -

-If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.2) to type long by numeric promotion (§5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

- -The built-in integer operators do not indicate overflow or underflow in any way. The only numeric operators that can throw an exception (§11) are the integer divide operator / (§15.16.2) and the integer remainder operator % (§15.16.3), which throw an ArithmeticException if the right-hand operand is zero.

- -The example:

-


-class Test {
-	public static void main(String[] args) {
-		int i = 1000000;
-		System.out.println(i * i);
-		long l = i;
-		System.out.println(l * l);
-		System.out.println(20296 / (l - i));
-	}
-}
-
-produces the output: -


--727379968
-1000000000000
-
-and then encounters an ArithmeticException in the division by l - i, because -l - i is zero. The first multiplication is performed in 32-bit precision, whereas the -second multiplication is a long multiplication. The value -727379968 is the decimal -value of the low 32 bits of the mathematical result, 1000000000000, which is -a value too large for type int. -

-Any value of any integral type may be cast to or from any numeric type. There are no casts between integral types and the type boolean.

- -

4.2.3 Floating-Point Types and Values

- -The floating-point types are float and double, representing the single-precision -32-bit and double-precision 64-bit format IEEE 754 values and operations as -specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE -Standard 754-1985 (IEEE, New York). -

-The IEEE 754 standard includes not only positive and negative sign-magnitude numbers, but also positive and negative zeros, positive and negative infinities, and a special Not-a-Number (hereafter abbreviated NaN). The NaN value is used to represent the result of certain operations such as dividing zero by zero. NaN constants of both float and double type are predefined as Float.NaN (§20.9.5) and Double.NaN (§20.10.5).

- -The finite nonzero values of type float are of the form , where s is +1 or -1, m is a positive integer less than , and e is an integer between -149 and 104, inclusive. Values of that form such that m is positive but less than and e is equal to -149 are said to be denormalized.

- -The finite nonzero values of type double are of the form , where s is +1 or -1, m is a positive integer less than , and e is an integer between -1075 and 970, inclusive. Values of that form such that m is positive but less than and e is equal to -1075 are said to be denormalized.

- -Except for NaN, floating-point values are ordered; arranged from smallest to largest, they are negative infinity, negative finite nonzero values, negative zero, positive zero, positive finite nonzero values, and positive infinity.

- -Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity. The operations Math.min and Math.max also distinguish positive zero and negative zero.

- -NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.19.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (§15.20.1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.

- -Any value of a floating-point type may be cast to or from any numeric type. There are no casts between floating-point types and the type boolean.

- -

4.2.4 Floating-Point Operations

- -Java provides a number of operators that act on floating-point values: -

-Other useful constructors, methods, and constants are predefined in the classes -Float (§20.9), Double (§20.10), and Math (§20.11). -

-If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

- -If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. (If the other operand is not a double, it is first widened to type double by numeric promotion (§5.6).) Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. If the other operand is not a float, it is first widened to type float by numeric promotion.

- -Operators on floating-point numbers behave exactly as specified by IEEE 754. In particular, Java requires support of IEEE 754 denormalized floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations in Java do not "flush to zero" if the calculated result is a denormalized number.

- -Java requires that floating-point arithmetic behave as if every floating-point operator rounded its floating-point result to the result precision. Inexact results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, the one with its least significant bit zero is chosen. This is the IEEE 754 standard's default rounding mode known as round to nearest.

- -Java uses round toward zero when converting a floating value to an integer (§5.1.3), which acts, in this case, as though the number were truncated, discarding the mantissa bits. Rounding toward zero chooses at its result the format's value closest to and no greater in magnitude than the infinitely precise result.

- -Java floating-point operators produce no exceptions (§11). An operation that overflows produces a signed infinity, an operation that underflows produces a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN.

- -The example program:

-


-class Test {
-
-	public static void main(String[] args) {
-
-		// An example of overflow:
-		double d = 1e308;
-		System.out.print("overflow produces infinity: ");
-		System.out.println(d + "*10==" + d*10);
-
-		// An example of gradual underflow:
-		d = 1e-305 * Math.PI;
-		System.out.print("gradual underflow: " + d + "\n      ");
-		for (int i = 0; i < 4; i++)
-			System.out.print(" " + (d /= 100000));
-		System.out.println();
-
-		// An example of NaN:
-		System.out.print("0.0/0.0 is Not-a-Number: ");
-		d = 0.0/0.0;
-		System.out.println(d);
-
-		// An example of inexact results and rounding:
-		System.out.print("inexact results with float:");
-		for (int i = 0; i < 100; i++) {
-			float z = 1.0f / i;
-			if (z * i != 1.0f)
-				System.out.print(" " + i);
-		}
-		System.out.println();
-
-		// Another example of inexact results and rounding:
-		System.out.print("inexact results with double:");
-		for (int i = 0; i < 100; i++) {
-			double z = 1.0 / i;
-			if (z * i != 1.0)
-				System.out.print(" " + i);
-		}
-		System.out.println();
-
-		// An example of cast to integer rounding:
-		System.out.print("cast to int rounds toward 0: ");
-		d = 12345.6;
-		System.out.println((int)d + " " + (int)(-d));
-	}
-}
-
-produces the output: -


-overflow produces infinity: 1.0e+308*10==Infinity
-gradual underflow: 3.141592653589793E-305
-	3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0
-0.0/0.0 is Not-a-Number: NaN
-inexact results with float: 0 41 47 55 61 82 83 94 97
-inexact results with double: 0 49 98
-cast to int rounds toward 0: 12345 -12345
-
-This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision.

- -The inexact results when i is 0 involve division by zero, so that z becomes positive infinity, and z * 0 is NaN, which is not equal to 1.0.

- -

4.2.5 The boolean Type and boolean Values

- -The boolean type represents a logical quantity with two possible values, indicated -by the literals true and false (§3.10.3). The boolean operators are: -

-Boolean expressions determine the control flow in several kinds of statements: -

-A boolean expression also determines which subexpression is evaluated in the -conditional ? : operator (§15.24). -

-Only boolean expressions can be used in control flow statements and as the first operand of the conditional operator ? :. An integer x can be converted to a boolean, following the C language convention that any nonzero value is true, by the expression x!=0. An object reference obj can be converted to a boolean, following the C language convention that any reference other than null is true, by the expression obj!=null.

- -A cast of a boolean value to type boolean is allowed (§5.1.1); no other casts on type boolean are allowed. A boolean can be converted to a string by string conversion (§5.4).

- -

4.3 Reference Types and Values

- -There are three kinds of reference types: class types (§8), interface types (§9), and -array types (§10). -

-Names are described in §6; type names in §6.5 and, specifically, §6.5.4. -

-The sample code:

-


class Point { int[] metrics; } -
interface Move { void move(int deltax, int deltay); } -
-declares a class type Point, an interface type Move, and uses an array type int[] -(an array of int) to declare the field metrics of the class Point. -

-

4.3.1 Objects

- -An object is a class instance or an array. -

-The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

- -A class instance is explicitly created by a class instance creation expression (§15.8), or by invoking the newInstance method of class Class (§20.3.8). An array is explicitly created by an array creation expression (§15.8).

- -A new class instance is implicitly created when the string concatenation operator + (§15.17.1) is used in an expression, resulting in a new object of type String (§4.3.3, §20.12). A new array object is implicitly created when an array initializer expression (§10.6) is evaluated; this can occur when a class or interface is initialized (§12.4), when a new instance of a class is created (§15.8), or when a local variable declaration statement is executed (§14.3).

- -Many of these cases are illustrated in the following example:

-


-class Point {
-	int x, y;
-	Point() { System.out.println("default"); }
-	Point(int x, int y) { this.x = x; this.y = y; }
-
-	// A Point instance is explicitly created at class initialization time:
-	static Point origin = new Point(0,0);
-
-	// A String can be implicitly created by a + operator:
-	public String toString() {
- return "(" + x + "," + y + ")";
- } -} -
-class Test { - public static void main(String[] args) { - // A Point is explicitly created using newInstance: - Point p = null; - try { - p = (Point)Class.forName("Point").newInstance(); - } catch (Exception e) { - System.out.println(e); - } -
- // An array is implicitly created by an array constructor: - Point a[] = { new Point(0,0), new Point(1,1) }; -
- // Strings are implicitly created by + operators: - System.out.println("p: " + p); - System.out.println("a: { " + a[0] + ", "
- + a[1] + " }"); -
- // An array is explicitly created by an array creation expression: - String sa[] = new String[2]; - sa[0] = "he"; sa[1] = "llo"; - System.out.println(sa[0] + sa[1]); - } -} -
-which produces the output: -


-default
-p: (0,0)
-a: { (0,0), (1,1) }
-hello
-
-The operators on references to objects are:

-

-There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.

- -The example program:

-

class Value { int val; }
-

-class Test {
-	public static void main(String[] args) {
-		int i1 = 3;
-		int i2 = i1;
-		i2 = 4;
-		System.out.print("i1==" + i1);
-		System.out.println(" but i2==" + i2);
-		Value v1 = new Value();
-		v1.val = 5;
-		Value v2 = v1;
-		v2.val = 6;
-		System.out.print("v1.val==" + v1.val);
-		System.out.println(" and v2.val==" + v2.val);
-	}
-}
-
-produces the output: -


-i1==3 but i2==4
-v1.val==6 and v2.val==6
-
-because v1.val and v2.val reference the same instance variable (§4.5.3) in the -one Value object created by the only new expression, while i1 and i2 are different -variables. -

-See §10 and §15.9 for examples of the creation and use of arrays.

- -Each object has an associated lock (§17.13), which is used by synchronized methods (§8.4.3) and the synchronized statement (§14.17) to provide control over concurrent access to state by multiple threads (§17.12, §20.20).

- -

4.3.2 The Class Object

- -The standard class Object is a superclass (§8.1) of all other classes. A variable of -type Object can hold a reference to any object, whether it is an instance of a class -or an array (§10). All class and array types inherit the methods of class Object, -which are summarized here and completely specified in §20.1: -

package java.lang;
-

-public class Object {
-	public final Class getClass() { . . . }
-	public String toString() { . . . }
-	public boolean equals(Object obj) { . . . }
-	public int hashCode() { . . . }
-	protected Object clone()
-		throws CloneNotSupportedException { . . . }
-	public final void wait()
- throws IllegalMonitorStateException,
- InterruptedException { . . . } - public final void wait(long millis) - throws IllegalMonitorStateException, - InterruptedException { . . . } - public final void wait(long millis, int nanos) { . . . } - throws IllegalMonitorStateException, - InterruptedException { . . . } - public final void notify() { . . . } - throws IllegalMonitorStateException - public final void notifyAll() { . . . } - throws IllegalMonitorStateException - protected void finalize() - throws Throwable { . . . } -} -
-The members of Object are as follows: -

-

4.3.3 The Class String

- -Instances of class String (§20.12) represent sequences of Unicode characters. -A String object has a constant (unchanging) value. String literals (§3.10.5) are -references to instances of class String. -

-The string concatenation operator + (§15.17.1) implicitly creates a new String object.

- -

4.3.4 When Reference Types Are the Same

- -Two reference types the same type if: -

-

4.4 Where Types Are Used

- -Types are used when they appear in declarations or in certain expressions. -

-The following code fragment contains one or more instances of each kind of usage of a type:

-


import java.util.Random; -

-class MiscMath {
-
int divisor; -
- MiscMath(int divisor) { - this.divisor = divisor; - } -
- float ratio(long l) { - try { - l /= divisor; - } catch (Exception e) { - if (e instanceof ArithmeticException) - l = Long.MAX_VALUE; - else - l = 0; - } - return (float)l; - } -
- double gausser() { - Random r = new Random(); - double[] val = new double[2]; - val[0] = r.nextGaussian(); - val[1] = r.nextGaussian(); - return (val[0] + val[1]) / 2; - } -
} -
-In this example, types are used in declarations of the following: -

-and in expressions of the following kinds: -

-

4.5 Variables

- -A variable is a storage location and has an associated type, sometimes called its -compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3). -A variable always contains a value that is assignment compatible (§5.2) with its -type. A variable's value is changed by an assignment (§15.25) or by a prefix or -postfix ++ (increment) or -- (decrement) operator (§15.13.2, §15.13.3, §15.14.1, -§15.14.2). -

-Compatibility of the value of a variable with its type is guaranteed by the design of the Java language. Default values are compatible (§4.5.4) and all assignments to a variable are checked for assignment compatibility (§5.2), usually at compile time, but, in a single case involving arrays, a run-time check is made (§10.10).

- -

4.5.1 Variables of Primitive Type

- -A variable of a primitive type always holds a value of that exact primitive type. -

-

4.5.2 Variables of Reference Type

- -A variable of reference type can hold either of the following: -

-

4.5.3 Kinds of Variables

- -There are seven kinds of variables: -

    - -
  1. A class variable is a field declared using the keyword static within a class declaration (§8.3.1.1), or with or without the keyword static within an interface declaration (§9.3). A class variable is created when its class or interface is loaded (§12.2) and is initialized to a default value (§4.5.4). The class variable effectively ceases to exist when its class or interface is unloaded (§12.8), after any necessary finalization of the class or interface (§12.6) has been completed. - -
  2. An instance variable is a field declared within a class declaration without using the keyword static (§8.3.1.1). If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.5.4) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.3). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed. - -
  3. Array components are unnamed variables that are created and initialized to default values (§4.5.4) whenever a new object that is an array is created (§15.9). The array components effectively cease to exist when the array is no longer referenced. See §10 for a description of arrays. - -
  4. Method parameters (§8.4.1) name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked (§15.11). The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete. - -
  5. Constructor parameters (§8.6.1) name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression (§15.8) or explicit constructor invocation (§8.6.5) invokes that constructor. The new variable is initialized with the corresponding argument value from the creation expression or constructor invocation. The constructor parameter effectively ceases to exist when the execution of the body of the constructor is complete. - -
  6. An exception-handler parameter is created each time an exception is caught by a catch clause of a try statement (§14.18). The new variable is initialized with the actual object associated with the exception (§11.3, §14.16). The exception-handler parameter effectively ceases to exist when execution of the block associated with the catch clause is complete. - -
  7. Local variables are declared by local variable declaration statements (§14.3). Whenever the flow of control enters a block (§14.2) or for statement (§14.12), a new variable is created for each local variable declared in a local variable declaration statement immediately contained within that block or for statement. A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (§16) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or for statement is complete. -
- -The following example contains several different kinds of variables:

-


-class Point {
-	static int numPoints;								// numPoints is a class variable
-	int x, y;								// x and y are instance variables
-	int[] w = new int[10];								// w[0] is an array component
-	int setX(int x) {								// x is a method parameter
-		int oldx = this.x;							// oldx is a local variable
-		this.x = x;
-		return oldx;
-	}
-}
-
-

4.5.4 Initial Values of Variables

- -Every variable in a Java program must have a value before its value is used: -

-The example program: -


-class Point {
-	static int npoints;
-	int x, y;
-	Point root;
-}
-
-class Test { - public static void main(String[] args) { - System.out.println("npoints=" + Point.npoints); - Point p = new Point(); - System.out.println("p.x=" + p.x + ", p.y=" + p.y); - System.out.println("p.root=" + p.root); - } -} -
-prints: -


-npoints=0
-p.x=0, p.y=0
-p.root=null
-
-illustrating the default initialization of npoints, which occurs when the class -Point is prepared (§12.3.2), and the default initialization of x, y, and root, which -occurs when a new Point is instantiated. See §12 for a full description of all -aspects of loading, linking, and initialization of classes and interfaces, plus a -description of the instantiation of classes to make new class instances. -

-

4.5.5 Variables Have Types, Objects Have Classes

- -Every object belongs to some particular class: the class that was mentioned in the -creation expression that produced the object, the class whose class object was -used to invoke the newInstance method (§20.3.6) to produce the object, or the -String class for objects implicitly created by the string concatenation operator + -(§15.17.1). This class is called the class of the object. (Arrays also have a class, as -described at the end of this section.) An object is said to be an instance of its class -and of all superclasses of its class. -

-(Sometimes a variable or expression is said to have a "run-time type" but that is an abuse of terminology; it refers to the class of the object referred to by the value of the variable or expression at run time, assuming that the value is not null. Properly speaking, type is a compile-time notion. A variable or expression has a type; an object or array has no type, but belongs to a class.)

- -The type of a variable is always declared, and the type of an expression can be deduced at compile time. The type limits the possible values that the variable can hold or the expression can produce at run time. If a run-time value is a reference that is not null, it refers to an object or array that has a class (not a type), and that class will necessarily be compatible with the compile-time type.

- -Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (§8.1.4) that interface.

- -Here is an example of creating new objects and of the distinction between the type of a variable and the class of an object:

-


-public interface Colorable {
-	void setColor(byte r, byte g, byte b);
-}
-
class Point { int x, y; } - -class ColoredPoint extends Point implements Colorable { -
byte r, g, b; -
- public void setColor(byte rv, byte gv, byte bv) { - r = rv; g = gv; b = bv; - } -
} -
-class Test { - public static void main(String[] args) { - Point p = new Point(); - ColoredPoint cp = new ColoredPoint(); - p = cp; - Colorable c = cp; - } -} -
-In this example: -

-Every array also has a class; the method getClass (§20.1.1), when invoked for an array object, will return a class object (of class Class) that represents the class of the array. The classes for arrays have strange names that are not valid Java identifiers; for example, the class for an array of int components has the name "[I" and so the value of the expression:

-

new int[10].getClass().getName()
-
-is the string "[I"; see §20.1.1 for details. -

- -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - -The Java Language Specification - Names - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 6

- -

Names

-

- -Names are used to refer to entities declared in a Java program. A declared -entity (§6.1) is a package, class type, interface type, member (field or method) of a -reference type, parameter (to a method, constructor, or exception handler), or -local variable. -

-Names in Java programs are either simple, consisting of a single identifier, or qualified, consisting of a sequence of identifiers separated by "." tokens (§6.2).

- -Every name introduced by a declaration has a scope (§6.3), which is the part of the Java program text within which the declared entity can be referred to by a simple name.

- -Packages and reference types (that is, class types, interface types, and array types) have members (§6.4). A member can be referred to using a qualified name N.x, where N is a simple or qualified name and x is an identifier. If N names a package, then x is a member of that package, which is either a class or interface type or a subpackage. If N names a reference type or a variable of a reference type, then x names a member of that type, which is either a field or a method.

- -In determining the meaning of a name (§6.5), Java uses the context of the occurrence to disambiguate among packages, types, variables, and methods with the same name.

- -Access control (§6.6) can be specified in a class, interface, method, or field declaration to control when access to a member is allowed. Access is a different concept from scope; access specifies the part of the Java program text within which the declared entity can be referred to by a qualified name, a field access expression (§15.10), or a method invocation expression (§15.11) in which the method is not specified by a simple name. The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are public, protected, and private.

- -Fully qualified names (§6.7) and naming conventions (§6.8) are also discussed in this chapter.

- -The name of a field, parameter, or local variable may be used as an expression (§15.13.1). The name of a method may appear in an expression only as part of a method invocation expression (§15.11). The name of a class or interface type may appear in an expression only as part of a class instance creation expression (§15.8), an array creation expression (§15.9), a cast expression (§15.15), or an instanceof expression (§15.19.2), or as part of a qualified name for a field or method. The name of a package may appear in an expression only as part of a qualified name for a class or interface type.

- -

6.1 Declarations

- -A declaration introduces an entity into a Java program and includes an identifier -(§3.8) that can be used in a name to refer to this entity. A declared entity is one of -the following: -

-Constructors (§8.6) are also introduced by declarations, but use the name of the -class in which they are declared rather than introducing a new name. -

-

6.2 Names and Identifiers

- -A name is used to refer to an entity declared in a Java program. -

-There are two forms of names: simple names and qualified names. A simple name is a single identifier. A qualified name consists of a name, a "." token, and an identifier.

- -In determining the meaning of a name (§6.5), the Java language takes into account the context in which the name appears. It distinguishes among contexts where a name must denote (refer to) a package (§6.5.3), a type (§6.5.4), a variable or value in an expression (§6.5.5), or a method (§6.5.6).

- -Not all identifiers in Java programs are a part of a name. Identifiers are also used in the following situations:

-

-In the example: -


-class Test {
-	public static void main(String[] args) {
-		Class c = System.out.getClass();
-		System.out.println(c.toString().length() +
-								args[0].length() + args.length);
-	}
-}
-
-the identifiers Test, main, and the first occurrences of args and c are not names; -rather, they are used in declarations to specify the names of the declared entities. -The names String, Class, System.out.getClass, System.out.println, -c.toString, args, and args.length appear in the example. The first occurrence -of length is not a name, but rather an identifier appearing in a method invocation -expression (§15.11). The second occurrence of length is not a name, but -rather an identifier appearing in a method invocation expression (§15.11). -

-The identifiers used in labeled statements and their associated break and continue statements are completely separate from those used in declarations. Thus, the following code is valid:

-


-class TestString {
-
char[] value; -

int offset, count; -
int indexOf(TestString str, int fromIndex) { - char[] v1 = value, v2 = str.value; - int max = offset + (count - str.count); - int start = offset + ((fromIndex < 0) ? 0 : fromIndex); - i: - for (int i = start; i <= max; i++)
- { - int n = str.count, j = i, k = str.offset; - while (n-- != 0) { - if (v1[j++] != v2[k++]) - continue i; - } - return i - offset; - } - return -1; - } -} -
-This code was taken from a version of the class String and its method indexOf -(§20.12.26), where the label was originally called test. Changing the label to -have the same name as the local variable i does not hide the label in the scope of -the declaration of i. The identifier max could also have been used as the statement -label; the label would not hide the local variable max within the labeled statement. -

-

6.3 Scope of a Simple Name

- -The scope of a declaration is the region of the program within which the entity -declared by the declaration can be referred to using a simple name: -


-	class Test {
-		int i = j;				// compile-time error: incorrect forward reference
-		int j = 1;
-	}
-

-	class Test {
-		Test() { k = 2; }
-		int j = 1;
-		int i = j;
-		int k;
-	}
-
-These rules imply that declarations of class and interface types need not appear -before uses of the types. -

-In the example:

-

package points;
-

-class Point {
-	int x, y;
-	PointList list;
-	Point next;
-}
-
-class PointList {
-	Point first;
-}
-
-the use of PointList in class Point is correct, because the scope of the class type -name PointList includes both class Point and class PointList, as well as any -other type declarations in other compilation units of package points. -

-

6.3.1 Hiding Names

- -Some declarations may be hidden (§6.3.1) in part of their scope by another declaration -of the same name, in which case a simple name cannot be used to refer to -the declared entity. -

-The example:

-


-class Test {
-	static int x = 1;
-	public static void main(String[] args) {
-		int x = 0;
-		System.out.print("x=" + x);
-		System.out.println(", Test.x=" + Test.x);
-	}
-}
-
-produces the output: -

x=0, Test.x=1
-
-This example declares: -

-Since the scope of a class variable includes the entire body of the class (§8.2) the class variable x would normally be available throughout the entire body of the method main. In this example, however, the class variable x is hidden within the body of the method main by the declaration of the local variable x.

- -A local variable has as its scope the rest of the block in which it is declared (§14.3.2); in this case this is the rest of the body of the main method, namely its initializer "0" and the invocations of print and println.

- -This means that:

-

-If the standard naming conventions (§6.8) are followed, then hiding that would make the identification of separate naming contexts matter should be rare. The following contrived example involves hiding because it does not follow the standard naming conventions:

-


-class Point { int x, y; }
-
-class Test {
-
-	static Point Point(int x, int y) {
-		Point p = new Point();
-		p.x = x; p.y = y;
-		return p;
-	}
-
- public static void main(String[] args) { - int Point; - Point[] pa = new Point[2]; - for (Point = 0; Point < 2; Point++) { - pa[Point] = new Point(); - pa[Point].x = Point; - pa[Point].y = Point; - } - System.out.println(pa[0].x + "," + pa[0].y); - System.out.println(pa[1].x + "," + pa[1].y); - Point p = Point(3, 4); - System.out.println(p.x + "," + p.y); - } -
} -
-This compiles without error and executes to produce the output: -


-0,0
-1,1
-3,4 -
-Within the body of main, the lookups of Point find different declarations depending -on the context of the use: -

-The example: -

import java.util.*;
-

-class Vector {
-	int val[] = { 1 , 2 };
-}
-
-class Test { - public static void main(String[] args) { - Vector v = new Vector(); - System.out.println(v.val[0]); - } -} -
-compiles and prints: -

1
-
-using the class Vector declared here in preference to class java.util.Vector -that might be imported on demand. -

-

6.4 Members and Inheritance

- -Packages and reference types have members. The members of a package (§7) are -subpackages (§7.1) and all the class (§8) and interface (§9) types declared in all -the compilation units (§7.3) of the package. The members of a reference type -(§4.3) are fields (§8.3, §9.3, §10.7) and methods (§8.4, §9.4). Members are either -declared in the type, or inherited because they are accessible members of a superclass -or superinterface which are neither hidden nor overridden (§8.4.6). -

-This section provides an overview of the members of packages and reference types here, as background for the discussion of qualified names and the determination of the meaning of names. For a complete description of membership, see §7.1, §8.2, §9.2, and §10.7.

- -

6.4.1 The Members of a Package

- -A member of a package (§7) is a subpackage (§7.1), or a class (§8) or interface -(§9) type declared in a compilation unit (§7.3) of the package. -

-In general, the subpackages of a package are determined by the host system (§7.2). However, the standard package java always includes the subpackages lang, util, io, and net and may include other subpackages. No two distinct members of the same package may have the same simple name (§7.1), but members of different packages may have the same simple name. For example, it is possible to declare a package:

-

package vector;
-public class Vector { Object[] vec; }
-
-that has as a member a public class named Vector, even though the standard -package java.util also declares a class named Vector. These two class types -are different, reflected by the fact that they have different fully qualified names -(§6.7). The fully qualified name of this example Vector is vector.Vector, -whereas java.util.Vector is the fully qualified name of the standard Vector -class. Because the package vector contains a class named Vector, it cannot also -have a subpackage named Vector. -

-

6.4.2 The Members of a Class Type

- -The members of a class type (§8.2) are fields and methods. The members of a -class type are all of the following: -

-Constructors (§8.6) are not members. -

-There is no restriction against a field and a method of a class type having the same simple name.

- -A class may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error (§6.5.6.2, §8.2).

- -In the example:

-


-interface Colors {
-	int WHITE = 0, BLACK = 1;
-}
-
-interface Separates {
-	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
-}
-
-class Test implements Colors, Separates {
-	public static void main(String[] args) {
-		System.out.println(BLACK); // compile-time error: ambiguous
-	}
-}
-
-the name BLACK in the method main is ambiguous, because class Test has two -members named BLACK, one inherited from Colors and one from Separates. -

-A class type may have two or more methods with the same simple name if the methods have different signatures (§8.4.2), that is, if they have different numbers of parameters or different parameter types in at least one parameter position. Such a method member name is said to be overloaded.

- -A class type may contain a declaration for a method with the same name and the same signature as a method that would otherwise be inherited from a superclass or superinterface. In this case, the method of the superclass or superinterface is not inherited. If the method not inherited is abstract, then the new declaration is said to implement it; if the method not inherited is not abstract, then the new declaration is said to override it.

- -In the example:

-


-class Point {
-	float x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	void move(float dx, float dy) { x += dx; y += dy; }
-	public String toString() { return "("+x+","+y+")"; }
-}
-
-the class Point has two members that are methods with the same name, move. -The overloaded move method of class Point chosen for any particular method -invocation is determined at compile time by the overloading resolution procedure -given in §15.11. -

-In this example, the members of the class Point are the float instance variables x and y declared in Point, the two declared move methods, the declared toString method, and the members that Point inherits from its implicit direct superclass Object (§4.3.2), such as the method hashCode (§20.1.4). Note that Point does not inherit the toString method (§20.1.2) of class Object because that method is overridden by the declaration of the toString method in class Point.

- -

6.4.3 The Members of an Interface Type

- -The members of an interface type (§9.2) are fields and methods. The members of -an interface are all of the following: -

-An interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any such field by its simple name results in a compile-time error (§6.5.5.1, §9.2).

- -In the example:

-


-interface Colors {
-	int WHITE = 0, BLACK = 1;
-}
-
-interface Separates {
-	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
-}
-interface ColorsAndSeparates extends Colors, Separates {
- int DEFAULT = BLACK; // compile-time error: ambiguous
-} -
-the members of the interface ColorsAndSeparates include those members -inherited from Colors and those inherited from Separates, namely WHITE, -BLACK (first of two), CYAN, MAGENTA, YELLOW, and BLACK (second of two). The -member name BLACK is ambiguous in the interface ColorsAndSeparates. -

-

6.4.4 The Members of an Array Type

- -The members of an array type (§10.7) are all of the following: -

-The example: -


-class Test {
-	public static void main(String[] args) {
-		int[] ia = new int[3];
-		int[] ib = new int[6];
-		System.out.println(ia.getClass() == ib.getClass());
-		System.out.println("ia has length=" + ia.length);
-	}
-}
-
-produces the output: -


-true
-ia has length=3
-
-This example uses the method getClass inherited from class Object and the -field length. The result of the comparison of the Class objects in the second -println demonstrates that all arrays whose components are of type int are -instances of the same array type, which is int[]. -

-

6.5 Determining the Meaning of a Name

- -The meaning of a name in Java depends on the context in which it is used. The -determination of the meaning of a name requires three steps. First, context causes -a name syntactically to fall into one of five categories: PackageName, TypeName, -ExpressionName, MethodName, or AmbiguousName. Second, a name that is initially -classified by its context as an AmbiguousName is then reclassified by certain -scoping rules to be a PackageName, TypeName, or ExpressionName. Third, the -resulting category then dictates the final determination of the meaning of the name -(or a compilation error if the name has no meaning). -

-Java's use of context helps to minimize name conflicts between entities of different kinds. Such conflicts will be rare if the naming conventions described in §6.8 are followed. Nevertheless, conflicts may arise unintentionally as types developed by different programmers or different organizations evolve. For example, types, methods, and fields may have the same name. Java never has trouble distinguishing between a method and a field with the same name, since the context of a use always tells whether a method or a field is intended.

- -

6.5.1 Syntactic Classification of a Name According to Context

- -A name is syntactically classified as a PackageName in these contexts: -

-A name is syntactically classified as a TypeName in these contexts: -

-A name is syntactically classified as an ExpressionName in these contexts: -

-A name is syntactically classified as a MethodName in this context: -

-A name is syntactically classified as an AmbiguousName in these contexts: -

-

6.5.2 Reclassification of Contextually Ambiguous Names

- -An AmbiguousName is then reclassified as follows: -

-As an example, consider the following contrived "library code":

-


package ORG.rpgpoet; -

import java.util.Random; -
interface Music { Random[] wizards = new Random[4]; } -
-and then consider this example code in another package: -


package bazola; -

-class Gabriel {
-	static int n = ORG.rpgpoet.Music.wizards.length;
-}
-
-First of all, the name ORG.rpgpoet.Music.wizards.length is classified as an -ExpressionName because it functions as a PostfixExpression. Therefore, each of -the names: -


-ORG.rpgpoet.Music.wizards
-ORG.rpgpoet.Music
-ORG.rpgpoet
-ORG
-
-is initially classified as an AmbiguousName. These are then reclassified: -

-

6.5.3 Meaning of Package Names

- -The meaning of a name classified as a PackageName is determined as follows. -

-

6.5.3.1 Simple Package Names

- -If a package name consists of a single Identifier, then this identifier denotes a top- -level package named by that identifier. If no package of that name is accessible, as -determined by the host system (§7.4.3), then a compile-time error occurs. -

-

6.5.3.2 Qualified Package Names

- -If a package name is of the form Q.Id, then Q must also be a package name. The -package name Q.Id names a package that is the member named Id within the -package named by Q. If Q does not name an accessible package or Id does not -name an accessible subpackage of that package, then a compile-time error occurs. -

-

6.5.4 Meaning of Type Names

- -The meaning of a name classified as a TypeName is determined as follows. -

-

6.5.4.1 Simple Type Names

- -If a type name consists of a single Identifier, then the identifier must occur in the -scope of a declaration of a type with this name, or a compile-time error occurs. It -is possible that the identifier occurs within the scope of more than one type with -that name, in which case the type denoted by the name is determined as follows: -

-This order for considering type declarations is designed to choose the most -explicit of two or more applicable type declarations. -

-

6.5.4.2 Qualified Type Names

- -If a type name is of the form Q.Id, then Q must be a package name. The type -name Q.Id names a type that is the member named Id within the package named -by Q. If Q does not name an accessible package, or Id does not name a type within -that package, or the type named Id within that package is not accessible (§6.6), -then a compile-time error occurs. -

-The example:

-

package wnj.test;
-

-class Test {
-	public static void main(String[] args) {
-		java.util.Date date =
-			new java.util.Date(System.currentTimeMillis());
-		System.out.println(date.toLocaleString());
-	}
-}
-
-produced the following output the first time it was run: -

Sun Jan 21 22:56:29 1996
-
-In this example: -

-

6.5.5 Meaning of Expression Names

- -The meaning of a name classified as an ExpressionName is determined as follows. -

-

6.5.5.1 Simple Expression Names

- -If an expression name consists of a single Identifier, then: -

-In the example: -


-class Test {
-
static int v; -

static final int f = 3; -
- public static void main(String[] args) { - int i; - i = 1; - v = 2; - f = 33; // compile-time error - System.out.println(i + " " + v + " " + f); - } -
} -
-the names used as the left-hand-sides in the assignments to i, v, and f denote the -local variable i, the field v, and the value of f (not the variable f, because f is a -final variable). The example therefore produces an error at compile time -because the last assignment does not have a variable as its left-hand side. If the -erroneous assignment is removed, the modified code can be compiled and it will -produce the output: -

1 2 3
-
-

6.5.5.2 Qualified Expression Names

- -If an expression name is of the form Q.Id, then Q has already been classified as a -package name, a type name, or an expression name: -

-The example: -


-class Point {
-	int x, y;
-	static int nPoints;
-}
-
-class Test {
-	public static void main(String[] args) {
-		int i = 0;
-		i.x++;								// compile-time error
-		Point p = new Point();
-		p.nPoints();								// compile-time error
-	}
-}
-
-encounters two compile-time errors, because the int variable i has no members, -and because nPoints is not a method of class Point. -

-

6.5.6 Meaning of Method Names

- -A MethodName can appear only in a method invocation expression (§15.11). The -meaning of a name classified as a MethodName is determined as follows. -

-

6.5.6.1 Simple Method Names

- -If a method name consists of a single Identifier, then Identifier is the method name -to be used for method invocation. The Identifier must name at least one method of -the class or interface within whose declaration the Identifier appears. See §15.11 -for further discussion of the interpretation of simple method names in method -invocation expressions. -

-

6.5.6.2 Qualified Method Names

- -If a method name is of the form Q.Id, then Q has already been classified as a -package name, a type name, or an expression name. If Q is a package name, then a -compile-time error occurs. Otherwise, Id is the method name to be used for -method invocation. If Q is a type name, then Id must name at least one static -method of the type Q. If Q is an expression name, then let T be the type of the -expression Q; Id must name at least one method of the type T. See §15.11 for further -discussion of the interpretation of qualified method names in method invocation -expressions. -

-

6.6 Qualified Names and Access Control

- -Qualified names are a means of access to members of packages and reference -types; related means of access include field access expressions (§15.10) and -method invocation expressions (§15.11). All three are syntactically similar in that -a "." token appears, preceded by some indication of a package, type, or expression -having a type and followed by an Identifier that names a member of the package -or type. These are collectively known as constructs for qualified access. -

-Java provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. Access control applies to qualified access and to the invocation of constructors by class instance creation expressions (§15.8), explicit constructor invocations (§8.6.5), and the method newInstance of class Class (§20.3.6).

- -If access is permitted, then the accessed entity is said to be accessible.

- -

6.6.1 Determining Accessibility

- -

6.6.2 Details on protected Access

- -A protected member or constructor of an object may be accessed from outside -the package in which it is declared only by code that is responsible for the implementation -of that object. Let C be the class in which a protected member or constructor -is declared and let S be the subclass of C in whose declaration the use of -the protected member or constructor occurs. Then: -

-

6.6.3 An Example of Access Control

- -For examples of access control, consider the two compilation units: -


package points; -
class PointVec { Point[] vec; } -
-and: -


package points; -

-public class Point {
-	protected int x, y;
-	public void move(int dx, int dy) { x += dx; y += dy; }
-	public int getX() { return x; }
-	public int getY() { return y; }
-}
-
-which declare two class types in the package points: -

-See §6.6.7 for an example of how the protected access modifier limits access. -

-

6.6.4 Example: Access to public and Non-public Classes

- -If a class lacks the public modifier, access to the class declaration is limited to -the package in which it is declared (§6.6). In the example: -


package points; -

-public class Point {
-	public int x, y;
-	public void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-class PointList { - Point next, prev; -} -
-two classes are declared in the compilation unit. The class Point is available outside -the package points, while the class PointList is available for access only -within the package. Thus a compilation unit in another package can access -points.Point, either by using its fully qualified name: -


package pointsUser; -

-class Test {
-	public static void main(String[] args) {
-		points.Point p = new points.Point();
-		System.out.println(p.x + " " + p.y);
-	}
-}
-
-or by using a single-type-import declaration (§7.5.1) that mentions the fully -qualfied name, so that the simple name may be used thereafter: -


package pointsUser; -

import points.Point; -

-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		System.out.println(p.x + " " + p.y);
-	}
-}
-
-However, this compilation unit cannot use or import points.PointList, which -is not declared public and is therefore inaccessible outside package points. -

-

6.6.5 Example: Default-Access Fields, Methods, and Constructors

- -If none of the access modifiers public, protected, or private are specified, a -class member or constructor is accessible throughout the package that contains the -declaration of the class in which the class member is declared, but the class member -or constructor is not accessible in any other package. If a public class has a -method or constructor with default access, then this method or constructor is not -accessible to or inherited by a subclass declared outside this package. -

-For example, if we have:

-


package points; -

-public class Point {
-	public int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	public void moveAlso(int dx, int dy) { move(dx, dy); }
-}
-
-then a subclass in another package may declare an unrelated move method, with -the same signature (§8.4.2) and return type. Because the original move method is -not accessible from package morepoints, super may not be used: -


package morepoints; -

-public class PlusPoint extends points.Point {
-	public void move(int dx, int dy) {
-		super.move(dx, dy);								// compile-time error
-		moveAlso(dx, dy);
-	}
-}
-
-Because move of Point is not overridden by move in PlusPoint, the method -moveAlso in Point never calls the method move in PlusPoint. -

-Thus if you delete the super.move call from PlusPoint and execute the test program:

-


-import points.Point;
-
-import morepoints.PlusPoint;
-
-class Test {
-
-    public static void main(String[] args) {
-        PlusPoint pp = new PlusPoint();
-        pp.move(1, 1);
-    }
-
} -
-it terminates normally. If move of Point were overridden by move in PlusPoint, -then this program would recurse infinitely, until a StackoverflowError -occurred. -

-

6.6.6 Example: public Fields, Methods, and Constructors

- -A public class member or constructor is accessible throughout the package -where it is declared and from any other package that has access to the package in -which it is declared (§7.4.4). For example, in the compilation unit: -


package points; -

-public class Point {
-
int x, y; -
- public void move(int dx, int dy) { - x += dx; y += dy; - moves++; - } -

public static int moves = 0; -
} -
-the public class Point has as public members the move method and the moves -field. These public members are accessible to any other package that has access -to package points. The fields x and y are not public and therefore are accessible -only from within the package points. -

-

6.6.7 Example: protected Fields, Methods, and Constructors

- -Consider this example, where the point package declares: -


package points; -

-public class Point {
-
protected int x, y; -
- void warp(threePoint.Point3d a) { - if (a.z > 0) // compile-time error: cannot access a.z - a.delta(this); - } -
} -
-and the threePoint package declares: -


package threePoint; -

import points.Point; -

-public class Point3d extends Point {
-
protected int z; -
- public void delta(Point p) { - p.x += this.x; // compile-time error: cannot access p.x - p.y += this.y; // compile-time error: cannot access p.y - } -
- public void delta3d(Point3d q) { - q.x += this.x; - q.y += this.y; - q.z += this.z; - } -
} -
-which defines a class Point3d. A compile-time error occurs in the method delta -here: it cannot access the protected members x and y of its parameter p, because -while Point3d (the class in which the references to fields x and y occur) is a subclass -of Point (the class in which x and y are declared), it is not involved in the -implementation of a Point (the type of the parameter p). The method delta3d -can access the protected members of its parameter q, because the class Point3d is -a subclass of Point and is involved in the implementation of a Point3d. -

-The method delta could try to cast (§5.4, §15.15) its parameter to be a Point3d, but this cast would fail, causing an exception, if the class of p at run time were not Point3d.

- -A compile-time error also occurs in the method warp: it cannot access the protected member z of its parameter a, because while the class Point (the class in which the reference to field z occurs) is involved in the implementation of a Point (the type of the parameter a), it is not a subclass of Point (the class in which z is declared).

- -

6.6.8 Example: private Fields, Methods, and Constructors

- -A private class member or constructor is accessible only within the class body in -which the member is declared and is not inherited by subclasses. In the example: -


-class Point {
-
Point() { setMasterID(); } -
- int x, y; - private int ID; - private static int masterID = 0; -
private void setMasterID() { ID = masterID++; } -
} -
-the private members ID, masterID, and setMasterID may be used only -within the body of class Point. They may not be accessed by qualified names, -field access expressions, or method invocation expressions outside the body of the -declaration of Point. -

-See §8.6.8 for an example that uses a private constructor.

- -

6.7 Fully Qualified Names

- -Every package, class, interface, array type, and primitive type has a fully qualified -name. It follows that every type except the null type has a fully qualified name. -

-Examples: -

-In the example: -

package points;
-

-class Point { int x, y; }
-
-class PointVec {
-	Point[] vec;
-}
-
-the fully qualified name of the type Point is "points.Point"; the fully qualified -name of the type PointVec is "points.PointVec"; and the fully qualified name -of the type of the field vec of class PointVec is "points.Point[]". -

-

6.8 Naming Conventions

- -The Java system and standard classes attempt to use, whenever possible, names -chosen according to the conventions presented here. These conventions help to -make code more readable and avoid certain kinds of name conflicts. -

-We recommend these conventions for use in all Java programs. However, these conventions should not be followed slavishly if long-held conventional usage dictates otherwise. So, for example, the sin and cos methods of the class java.lang.Math have mathematically conventional names, even though these method names flout Java convention because they are short and are not verbs.

- -

6.8.1 Package Names

- -Names of packages that are to be made widely available should be formed as -described in §7.7. Such names are always qualified names whose first identifier -consists of two or three uppercase letters that name an Internet domain, such as -COM, EDU, GOV, MIL, NET, ORG, or a two-letter ISO country code such as UK or JP. -Here are examples of hypothetical unique names that might be formed under this -convention: -


-COM.JavaSoft.jag.Oak
-ORG.NPR.pledge.driver
-UK.ac.city.rugby.game
-
-Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved to JavaSoft for naming standard Java packages.

- -When package names occur in expressions:

-

-

6.8.2 Class and Interface Type Names

- -Names of class types should be descriptive nouns or noun phrases, not overly -long, in mixed case with the first letter of each word capitalized. For example: -


-ClassLoader
-SecurityManager
-Thread
-Dictionary
-BufferedInputStream
-
-Likewise, names of interface types should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces java.io.DataInput and java.io.DataOutput; or it may be an adjective describing a behavior, as for the interfaces java.lang.Runnable and java.lang.Cloneable.

- -Hiding involving class and interface type names is rare. Names of fields, parameters, and local variables normally do not hide type names because they conventionally begin with a lowercase letter whereas type names conventionally begin with an uppercase letter.

- -

6.8.3 Method Names

- -Method names should be verbs or verb phrases, in mixed case, with the first letter -lowercase and the first letter of any subsequent words capitalized. Here are some -additional specific conventions for method names: -

-Whenever possible and appropriate, basing the names of methods in a new class -on names in an existing class that is similar, especially a class from the standard -Java Application Programming Interface classes, will make it easier to use. -

-Method names cannot hide or be hidden by other names (§6.5.6).

- -

6.8.4 Field Names

- -Names of fields that are not final should be in mixed case with a lowercase first -letter and the first letters of subsequent words capitalized. Note that well-designed -Java classes have very few public or protected fields, except for fields that are -constants (final static fields) (§6.8.5). -

-Fields should have names that are nouns, noun phrases, or abbreviations for nouns. Examples of this convention are the fields buf, pos, and count of the class java.io.ByteArrayInputStream (§22.6) and the field bytesTransferred of the class java.io.InterruptedIOException (§22.30.1).

- -Hiding involving field names is rare.

-

-

6.8.5 Constant Names

- -The names of constants in interface types should be, and final variables of class -types may conventionally be, a sequence of one or more words, acronyms, or -abbreviations, all uppercase, with components separated by underscore "_" characters. -Constant names should be descriptive and not unnecessarily abbreviated. -Conventionally they may be any appropriate part of speech. Examples of names -for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the -class java.lang.Character. -

-A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:

-


-interface ProcessStates {
-	int PS_RUNNING = 0;
-	int PS_SUSPENDED = 1;
-}
-
-Hiding involving constant names is rare: -

-

6.8.6 Local Variable and Parameter Names

- -Local variable and parameter names should be short, yet meaningful. They are -often short sequences of lowercase letters that are not words. For example: -

-One-character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type. Conventional one-character names are:

-

-Local variable or parameter names that consist of only two or three uppercase letters should be avoided to avoid potential conflicts with the initial country codes and domain names that are the first component of unique package names (§7.7).

- -

- - -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - -The Java Language Specification - Packages - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 7

- -

Packages

-

- -Java programs are organized as sets of packages. Each package has its own set -of names for types, which helps to prevent name conflicts. A type is accessible -(§6.6) outside the package that declares it only if the type is declared public. -

-The naming structure for packages is hierarchical (§7.1). The members of a package are class and interface types (§7.6), which are declared in compilation units of the package, and subpackages, which may contain compilation units and subpackages of their own.

- -A package can be stored in a file system (§7.2.1) or in a database (§7.2.2). Packages that are stored in a file system have certain constraints on the organization of their compilation units to allow a simple implementation to find classes easily. In either case, the set of packages available to a Java program is determined by the host system, but must always include at least the three standard packages java.lang, java.util, and java.io as specified in Chapters 20, 21, and 22. In most host environments, the standard packages java.applet, java.awt, and java.net, which are not described in this specification, are also available to Java programs.

- -A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports each of the types declared in the predefined package java.lang.

- -A compilation unit has three parts, each of which is optional:

-

-For small programs and casual development, a package can be unnamed (§7.4.2) or have a simple name, but if Java code is to be widely distributed, unique package names should be chosen (§7.7). This can prevent the conflicts that would otherwise occur if two development groups happened to pick the same package name and these packages were later to be used in a single program.

- -

7.1 Package Members

- -A package can have members of either or both of the following kinds: -

-For example, in the standard Java Application Programming Interface: -

-If the fully qualified name (§6.7) of a package is P, and Q is a subpackage of P, -then P.Q is the fully qualified name of the subpackage. -

-The subpackages of package java named lang, util, and io (whose fully qualified package names are therefore java.lang, java.util, and java.io) are a standard part of every Java implementation and are specified in Chapters 20, 21, and 22. Many Java implementations will include the entire set of java packages defined in the series of books The Java Application Programming Interface.

- -A package may not contain a type declaration and a subpackage of the same name, or a compile-time error results. Here are some examples:

-

-The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in the Java language itself other than the prohibition against a package having a subpackage with the same simple name as a type declared in that package. There is no special access relationship in the Java language between a package named oliver and another package named oliver.twist, or between packages named evelyn.wood and evelyn.Waugh. For example, the code in a package named oliver.twist has no better access to the types declared within package oliver than code in any other package.

- -

7.2 Host Support for Packages

- -Each Java host determines how packages, compilation units, and subpackages are -created and stored; which top-level package names are in scope in a particular -compilation; and which packages are accessible. -

-The packages may be stored in a local file system in simple implementations of Java. Other implementations may use a distributed file system or some form of database to store Java source and/or binary code.

- -

7.2.1 Storing Packages in a File System

- -As an extremely simple example, all the Java packages and source and binary -code on a system might be stored in a single directory and its subdirectories. Each -immediate subdirectory of this directory would represent a top-level package, that -is, one whose fully qualified name consists of a single simple name. The directory -might contain the following immediate subdirectories: -


-COM
-gls
-jag
-java
-wnj
-
-where directory java would contain the standard Java Application Programming -Interface packages that are part of every standard Java system; the directories jag, -gls, and wnj might contain packages that the three authors of this specification -created for their personal use and to share with each other within this small group; -and the directory COM would contain packages procured from companies that used -the conventions described in §7.7 to generate unique names for their packages. -

-Continuing the example, the directory java would probably contain at least the following subdirectories:

-


-applet	
-awt
-io
-lang
-net
-util
-
-corresponding to the standard packages java.applet, java.awt, java.io, -java.lang, java.net, and java.util that are defined as part of the standard -Java Application Programming Interface. -

-Still continuing the example, if we were to look inside the directory util, we might see the following files:

-


-BitSet.java										Observable.java
-BitSet.class										Observable.class
-Date.java										Observer.java
-Date.class										Observer.class
-Dictionary.java										Properties.java
-Dictionary.class										Properties.class
-EmptyStackException.java										Random.java
-EmptyStackException.class										Random.class
-Enumeration.java										Stack.java
-Enumeration.class										Stack.class
-Hashtable.java										StringTokenizer.java
-Hashtable.class										StringTokenizer.class
-NoSuchElementException.java										Vector.java
-NoSuchElementException.class										Vector.class
-
-where each of the .java files contains the source for a compilation unit (§7.3) -that contains the definition of a class or interface whose binary compiled form is -contained in the corresponding .class file. -

-Under this simple organization of packages, an implementation of Java would transform a package name into a pathname by concatenating the components of the package name, placing a file name separator (directory indicator) between adjacent components. For example, if this simple organization were used on a UNIX system, where the file name separator is /, the package name:

-

jag.scrabble.board
-
-would be transformed into the directory name: -

jag/scrabble/board
-
-and: -

COM.Sun.sunsoft.DOE
-
-would be transformed to the directory name: -

COM/Sun/sunsoft/DOE
-
-In fact, the standard JavaSoft Java Developer's Kit on UNIX differs from the very simple discipline described here only in that it provides a CLASSPATH environment variable that specifies a set of directories, each of which is treated like the single directory described here. These directories are searched in order for definitions of named packages and types.

- -A package name component or class name might contain a character that cannot correctly appear in a host file system's ordinary directory name, such as a Unicode character on a system that allows only ASCII characters in file names. As a convention, the character can be escaped by using, say, the @ character followed by four hexadecimal digits giving the numeric value of the character, as in the \uxxxx escape (§3.3), so that the package name:

-

children.activities.crafts.papierM\u00e2ch\u00e9
-
-which can also be written using full Unicode as: -

children.activities.crafts.papierMâché
-
-might be mapped to the directory name: -

children/activities/crafts/papierM@00e2ch@00e9
-
-If the @ character is not a valid character in a file name for some given host file -system, then some other character that is not valid in a Java identifier could be -used instead. -

-

7.2.2 Storing Packages in a Database

- -A host system may store packages and their compilation units and subpackages in -a database. -

-Java allows such a database to relax the restrictions (§7.6) on compilation units in file-based implementations. For example, a system that uses a database to store packages need not enforce a maximum of one public class or interface per compilation unit. Systems that use a database must, however, provide an option to convert a Java program to a form that obeys the restrictions, for purposes of export to file-based implementations.

- -

7.3 Compilation Units

- -CompilationUnit is the goal symbol (§2.1) for the syntactic grammar (§2.3) of -Java programs. It is defined by the following productions: -

-Types declared in different compilation units can depend on each other, circularly. -A Java compiler must arrange to compile all such types at the same time. -

-A compilation unit consists of three parts, each of which is optional:

-

-Every compilation unit automatically and implicitly imports every public type name declared in the predefined package java.lang, so that the names of all those types are available as simple names, as described in §7.5.3.

- -

7.4 Package Declarations

- -A package declaration appears within a compilation unit to indicate the package -to which the compilation unit belongs. A compilation unit that has no package -declaration is part of an unnamed package. -

-

7.4.1 Named Packages

- -A package declaration in a compilation unit specifies the name (§6.2) of the package -to which the compilation unit belongs. -

-The package name mentioned in a package declaration must be the fully qualified -name (§6.7) of the package. -

-If a type named T is declared in a compilation unit of a package whose fully qualified name is P, then the fully qualified name of the type is P.T; thus in the example:

-

package wnj.points;
-class Point { int x, y; }
-
-the fully qualified name of class Point is wnj.points.Point. -

-

7.4.2 Unnamed Packages

- -A compilation unit that has no package declaration is part of an unnamed package. -As an example, the compilation unit: -


-class FirstCall {
-	public static void main(String[] args) {
-		System.out.println("Mr. Watson, come here. "
-									+ "I want you.");
-	}
-}
-
-defines a very simple compilation unit as part of an unnamed package. -

-A Java system must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.

- -In Java systems that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is available at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.

- -Unnamed packages are provided by Java principally for convenience when developing small or temporary applications or when just beginning development.

- -Caution must be taken when using unnamed packages. It is possible for a compilation unit in a named package to import a type from an unnamed package, but the compiled version of this compilation unit will likely then work only when that particular unnamed package is "current." For this reason, it is strongly recommended that compilation units of named packages never import types from unnamed packages. It is also recommended that any type declared in an unnamed package not be declared public, to keep them from accidentally being imported by a named package.

- -It is recommended that a Java system provide safeguards against unintended consequences in situations where compilation units of named packages import types from unnamed packages. One strategy is to provide a way to associate with each named package at most one unnamed package, and then to detect and warn about situations in which a named package is used by more than one unnamed package. It is specifically not required-indeed, it is strongly discouraged-for an implementation to support use of a named package by more than one unnamed package by maintaining multiple compiled versions of the named package.

- -

7.4.3 Scope and Hiding of a Package Name

- -Which top-level package names are in scope (§6.3, §6.5) is determined by conventions -of the host system. -

-Package names never hide other names.

- -

7.4.4 Access to Members of a Package

- -Whether access to members of a package is allowed is determined by the host system. -The package java should always be accessible, and its standard subpackages -lang, io, and util should always be accessible. -

-It is strongly recommended that the protections of a file system or database used to store Java programs be set to make all compilation units of a package available whenever any of the compilation units is available.

- -

7.5 Import Declarations

- -An import declaration allows a type declared in another package to be referred to -by a simple name (§6.2) that consists of a single identifier. Without the use of an -appropriate import declaration, the only way to refer to a type declared in another -package is to use its fully qualified name (§6.7). -

-A single-type-import declaration (§7.5.1) imports a single type, by mentioning its fully qualified name. A type-import-on-demand declaration (§7.5.2) imports all the public types of a named package as needed.

- -An import declaration makes types available by their simple names only within the compilation unit that actually contains the import declaration. The scope of the name(s) it introduces specifically does not include the package statement, other import statements in the current compilation unit, or other compilation units in the same package. Please see §7.5.4 for an illustrative example.

- -

7.5.1 Single-Type-Import Declaration

- -A single-type-import declaration imports a single type by giving its fully qualified -name, making it available under a simple name in the class and interface declarations -of its compilation unit. -

-The TypeName must be the fully qualified name of a class or interface type; a -compile-time error occurs if the named type does not exist. If the named type is -not in the current package, then it must be accessible (§6.6)-in an accessible -package and declared public (§8.1.2, §9.1.2)-or a compile-time error occurs. -

-The example:

-

import java.util.Vector;
-
-causes the simple name Vector to be available within the class and interface declarations -in a compilation unit. Thus, the simple name Vector refers to the type -Vector in the package java.util in all places where it is not hidden (§6.3) by a -declaration of a field, parameter, or local variable with the same name. -

-If two single-type-import declarations in the same compilation unit attempt to import types with the same simple name, then a compile-time error occurs, unless the two types are the same type, in which case the duplicate declaration is ignored. If another type with the same name is otherwise declared in the current compilation unit except by a type-import-on-demand declaration (§7.5.2), then a compile-time error occurs.

- -So the sample program:

-


import java.util.Vector; -
class Vector { Object[] vec; } -
-causes a compile-time error because of the duplicate declaration of Vector, as -does: -


import java.util.Vector; -
import myVector.Vector; -
-where myVector is a package containing the compilation unit: -


package myVector; -
public class Vector { Object[] vec; } -
-The compiler keeps track of types by their fully qualified names (§6.7). Simple names and fully qualified names may be used interchangeably whenever they are both available.

- -Note that an import statement cannot import a subpackage, only a type. For example, it does not work to try to import java.util and then use the name util.Random to refer to the type java.util.Random:

-


import java.util; // incorrect: compile-time error -
class Test { util.Random generator; } -
-

7.5.2 Type-Import-on-Demand Declaration

- -A type-import-on-demand declaration allows all public types declared in the -package named by a fully qualified name to be imported as needed. -

-It is a compile-time error for a type-import-on-demand declaration to name a -package that is not accessible (§6.6), as determined by the host system (§7.2). -Two or more type-import-on-demand declarations in the same compilation unit -may name the same package; the effect is as if there were exactly one such declaration. -It is not a compile-time error to name the current package or java.lang in -a type-import-on-demand declaration, even though they are already imported; the -duplicate type-import-on-demand declaration is ignored. -

-The example:

-

import java.util.*;
-
-causes the simple names of all public types declared in the package java.util -to be available within the class and interface declarations of the compilation unit. -Thus, the simple name Vector refers to the type Vector in the package -java.util in all places where it is not hidden (§6.3) by a single-type-import declaration -of a type whose simple name is Vector; by a type named Vector and -declared in the package to which the compilation unit belongs; or by a declaration -of a field, parameter, or local variable named Vector. (It would be unusual for any -of these conditions to occur.) -

-

7.5.3 Automatic Imports

- -Each compilation unit automatically imports each of the public type names -declared in the predefined package java.lang, as if the declaration: -

import java.lang.*;
-
-appeared at the beginning of each compilation unit, immediately following any -package statement. -

-The full specification of java.lang is given in Chapter 20. The following public types are defined in java.lang:

-


-AbstractMethodError										LinkageError
-ArithmeticException										Long
-ArrayStoreException										Math
-Boolean										NegativeArraySizeException
-Character										NoClassDefFoundError
-Class										NoSuchFieldError
-ClassCastException										NoSuchMethodError
-ClassCircularityError										NullPointerException
-ClassFormatError										Number
-ClassLoader										NumberFormatException
-ClassNotFoundException										Object
-CloneNotSupportedException										OutOfMemoryError
-Cloneable										Process
-Compiler										Runnable
-Double										Runtime
-Error										RuntimeException
-Exception										SecurityException
-ExceptionInInitializerError										SecurityManager
-Float										StackOverflowError
-IllegalAccessError										String
-IllegalAccessException										StringBuffer
-IllegalArgumentException										System
-IllegalMonitorStateException										Thread
-IllegalThreadStateException										ThreadDeath
-IncompatibleClassChangeError										ThreadGroup
-IndexOutOfBoundsException										Throwable
-InstantiationError										UnknownError
-InstantiationException										UnsatisfiedLinkError
-Integer										VerifyError
-InternalError										VirtualMachineError
-InterruptedException
-
-

7.5.4 A Strange Example

- -Package names and type names are usually different under the naming conventions -described in §6.8. Nevertheless, in a contrived example where there is an -unconventionally-named package Vector, which declares a public class named -Mosquito: -


package Vector; -
public class Mosquito { int capacity; } -
-and then the compilation unit: -


package strange.example; -

import java.util.Vector; -

import Vector.Mosquito; -

-class Test {
-	public static void main(String[] args) {
-		System.out.println(new Vector().getClass());
-		System.out.println(new Mosquito().getClass());
-	}
-}
-
-the single-type-import declaration (§7.5.1) importing class Vector from package -java.util does not prevent the package name Vector from appearing and being -correctly recognized in subsequent import declarations. The example compiles -and produces the output: -


-class java.util.Vector
-class Vector.Mosquito
-
-

7.6 Type Declarations

- -A type declaration declares a class type (§8) or an interface type (§9): -

-A Java compiler must ignore extra ";" tokens appearing at the level of type declarations. Stray semicolons are permitted in Java solely as a concession to C++ programmers who are used to writing:

-

class date { int month, day, year; };
-
-(In C++, but not in Java, one can provide a comma-separated list of identifiers in -order to declare variables between the "}" and the ";".) Extra semicolons should -not be used in new Java code. Software that reformats Java code can delete them. -

-By default, the types declared in a package are accessible only within the compilation units of that package, but a type may be declared to be public to grant access to the type from code in other packages (§6.6, §8.1.2, §9.1.2).

- -A Java implementation must keep track of types within packages by their fully qualified names (§6.7). Multiple ways of naming a type must be expanded to fully qualified names to make sure that such names are understood as referring to the same type. For example, if a compilation unit contains the single-type-import declaration (§7.5.1):

-

import java.util.Vector;
-
-then within that compilation unit the simple name Vector and the fully qualified -name java.util.Vector refer to the same type. -

-When Java packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

-

-This restriction implies that there must be at most one such type per compilation -unit. This restriction makes it easy for a Java compiler and Java Virtual Machine -to find a named class within a package; for example, the source code for a public -type wet.sprocket.Toad would be found in a file Toad.java in the directory -wet/sprocket, and the corresponding object code would be found in the file -Toad.class in the same directory. -

-When Java packages are stored in a database (§7.2.2), the host system need not enforce such restrictions.

- -In practice, many Java programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.

- -

7.7 Unique Package Names

- -Developers should take steps to avoid the possibility of two published packages -having the same name by choosing unique package names for packages that are -widely distributed. This allows packages to be easily and automatically installed -and catalogued. This section specifies a standard convention, not enforced by a -Java compiler, for generating such unique package names. Java systems are -encouraged to provide automatic support for converting a set of packages from -local and casual package names to the unique name format described here. -

-If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create a situation that is difficult or impossible for the user or programmer to resolve. The class ClassLoader (§20.14) of the standard Java Virtual Machine environment can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a naïve Java program.

- -You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as Sun.COM. You then reverse this name, component by component, to obtain, in this example, COM.Sun, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names.

- -Such a convention might specify that certain directory name components be division, department, project, machine, or login names. Some possible examples:

-


-COM.Sun.sunsoft.DOE
-COM.Sun.java.jag.scrabble
-COM.Apple.quicktime.v2
-EDU.cmu.cs.bovik.cheese
-GOV.whitehouse.socks.mousefinder
-
-The first component of a unique package name is always written in all-uppercase -ASCII letters and should be one of the top-level domain names, currently COM, -EDU, GOV, MIL, NET, ORG, or one of the English two-letter codes identifying countries -as specified in ISO Standard 3166, 1981. For more information, refer to the -documents stored at ftp://rs.internic.net/rfc, for example, rfc920.txt -and rfc1032.txt. -

-The name of a package is not meant to imply anything about where the package is stored within the Internet; for example, a package named EDU.cmu.cs.bovik.cheese is not necessarily obtainable from Internet address cmu.EDU or from cs.cmu.EDU or from bovik.cs.cmu.EDU. The Java convention for generating unique package names is merely a way to piggyback a package naming convention on top of an existing, widely known unique name registry instead of having to create a separate registry for Java package names.

- -If you need to get a new Internet domain name, you can get an application form from ftp://ftp.internic.net and submit the complete forms by E-mail to domreg@internic.net. To find out what the currently registered domain names are, you can telnet to rs.internic.net and use the whois facility.

- - -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - -The Java Language Specification - Classes - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 8

- -

Classes

-

- -Class declarations define new reference types and describe how they are -implemented (§8.1). -

-The name of a class has as its scope all type declarations in the package in which the class is declared (§8.1.1). A class may be declared abstract (§8.1.2.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. A class may be declared final (§8.1.2.2), in which case it cannot have subclasses. If a class is declared public, then it can be referred to from other packages.

- -Each class except Object is an extension of (that is, a subclass of) a single existing class (§8.1.3) and may implement interfaces (§8.1.4).

- -The body of a class declares members (fields and methods), static initializers, and constructors (§8.1.5). The scope of the name of a member is the entire declaration of the class to which the member belongs. Field, method, and constructor declarations may include the access modifiers (§6.6) public, protected, or private. The members of a class include both declared and inherited members (§8.2). Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.

- -Field declarations (§8.3) describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared final (§8.3.1.2), in which case it cannot be assigned to except as part of its declaration. Any field declaration may include an initializer; the declaration of a final field must include an initializer.

- -Method declarations (§8.4) describe code that may be invoked by method invocation expressions (§15.11). A class method is invoked relative to the class type; an instance method is invoked with respect to some particular object that is an instance of the class type. A method whose declaration does not indicate how it is implemented must be declared abstract. A method may be declared final (§8.4.3.3), in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent native code (§8.4.3.4). A synchronized method (§8.4.3.5) automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a synchronized statement (§14.17), thus allowing its activities to be synchronized with those of other threads (§17).

- -Method names may be overloaded (§8.4.7).

- -Static initializers (§8.5) are blocks of executable code that may be used to help initialize a class when it is first loaded (§12.4).

- -Constructors (§8.6) are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded (§8.6.6).

- -

8.1 Class Declaration

- -A class declaration specifies a new reference type: -

-If a class is declared in a named package (§7.4.1) with fully qualified name P -(§6.7), then the class has the fully qualified name P.Identifier. If the class is in an -unnamed package (§7.4.2), then the class has the fully qualified name Identifier. -In the example: -

class Point { int x, y; }
-
-the class Point is declared in a compilation unit with no package statement, and -thus Point is its fully qualified name, whereas in the example: -


-package vista;
-class Point { int x, y; }
-
-the fully qualified name of the class Point is vista.Point. (The package name -vista is suitable for local or personal use; if the package were intended to be -widely distributed, it would be better to give it a unique package name (§7.7).) -

-A compile-time error occurs if the Identifier naming a class appears as the name of any other class type or interface type declared in the same package (§7.6).

- -A compile-time error occurs if the Identifier naming a class is also declared as a type by a single-type-import declaration (§7.5.1) in the compilation unit (§7.3) containing the class declaration.

- -In the example:

-


-package test;
-
import java.util.Vector; -
-class Point { - int x, y; -} -
-interface Point { // compile-time error #1 - int getR(); - int getTheta(); -} -
class Vector { Point[] pts; } // compile-time error #2 -
-the first compile-time error is caused by the duplicate declaration of the name -Point as both a class and an interface in the same package. A second error -detected at compile time is the attempt to declare the name Vector both by a class -type declaration and by a single-type-import declaration. -

-Note, however, that it is not an error for the Identifier that names a class also to name a type that otherwise might be imported by a type-import-on-demand declaration (§7.5.2) in the compilation unit (§7.3) containing the class declaration. In the example:

-


-package test;
-
import java.util.*; -
class Vector { Point[] pts; } // not a compile-time error -
-the declaration of the class Vector is permitted even though there is also a class -java.util.Vector. Within this compilation unit, the simple name Vector refers -to the class test.Vector, not to java.util.Vector (which can still be referred -to by code within the compilation unit, but only by its fully qualified name). -

-

8.1.1 Scope of a Class Type Name

- -The Identifier in a class declaration specifies the name of the class. This class -name has as its scope (§6.3) the entire package in which the class is declared. As -an example, the compilation unit: -


package points; -

-class Point {
-	int x, y;									// coordinates
-	PointColor color;									// color of this point
-	Point next;									// next point with this color
- static int nPoints; -} -
-class PointColor { - Point first; // first point with this color - PointColor(int color) { - this.color = color; - } - private int color; // color components -} -
-defines two classes that use each other in the declarations of their class members. -Because the class type names Point and PointColor have the entire package -points, including the entire current compilation unit, as their scope, this example -compiles correctly-that is, forward reference is not a problem. -

-

8.1.2 Class Modifiers

- -A class declaration may include class modifiers. -

-The access modifier public is discussed in §6.6. A compile-time error occurs if -the same modifier appears more than once in a class declaration. If two or more -class modifiers appear in a class declaration, then it is customary, though not -required, that they appear in the order consistent with that shown above in the production -for ClassModifier. -

-

8.1.2.1 abstract Classes

- -An abstract class is a class that is incomplete, or to be considered incomplete. -Only abstract classes may have abstract methods (§8.4.3.1, §9.4), that is, -methods that are declared but not yet implemented. If a class that is not abstract -contains an abstract method, then a compile-time error occurs. A class has -abstract methods if any of the following is true: -

-In the example: -


-abstract class Point {
-	int x = 1, y = 1;
-	void move(int dx, int dy) {
-		x += dx;
-		y += dy;
-		alert();
-	}
-	abstract void alert();
-}
-
-abstract class ColoredPoint extends Point { - int color; -} -
-class SimplePoint extends Point { - void alert() { } -} -
-a class Point is declared that must be declared abstract, because it contains a -declaration of an abstract method named alert. The subclass of Point named -ColoredPoint inherits the abstract method alert, so it must also be declared -abstract. On the other hand, the subclass of Point named SimplePoint provides -an implementation of alert, so it need not be abstract. -

-A compile-time error occurs if an attempt is made to create an instance of an abstract class using a class instance creation expression (§15.8). An attempt to instantiate an abstract class using the newInstance method of class Class (§20.3.6) will cause an InstantiationException (§11.5.1) to be thrown. Thus, continuing the example just shown, the statement:

-

	Point p = new Point();
-
-would result in a compile-time error; the class Point cannot be instantiated -because it is abstract. However, a Point variable could correctly be initialized -with a reference to any subclass of Point, and the class SimplePoint is not -abstract, so the statement: -

	Point p = new SimplePoint();
-
-would be correct. -

-A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class. Thus, in the example just given, instantiation of a SimplePoint causes the default constructor and field initializers for x and y of Point to be executed.

- -It is a compile-time error to declare an abstract class type such that it is not possible to create a subclass that implements all of its abstract methods. This situation can occur if the class would have as members two abstract methods that have the same method signature (§8.4.2) but different return types. As an example, the declarations:

-


-interface Colorable { void setColor(int color); }
-
-abstract class Colored implements Colorable {
-	abstract int setColor(int color);
-}
-
-result in a compile-time error: it would be impossible for any subclass of class -Colored to provide an implementation of a method named setColor, taking one -argument of type int, that can satisfy both abstract method specifications, -because the one in interface Colorable requires the same method to return no -value, while the one in class Colored requires the same method to return a value -of type int (§8.4). -

-A class type should be declared abstract only if the intent is that subclasses can be created to complete the implementation. If the intent is simply to prevent instantiation of a class, the proper way to express this is to declare a constructor (§8.6.8) of no arguments, make it private, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables. The class java.lang.Math is an example of a class that cannot be instantiated; its declaration looks like this:

-


-public final class Math {
-
private Math() { } // never instantiate this class -

. . . declarations of class variables and methods . . . -
} -
-

8.1.2.2 final Classes

- -A class can be declared final if its definition is complete and no subclasses are -desired or required. A compile-time error occurs if the name of a final class -appears in the extends clause (§8.1.3) of another class declaration; this implies -that a final class cannot have any subclasses. A compile-time error occurs if a -class is declared both final and abstract, because the implementation of such a -class could never be completed (§8.1.2.1). -

-Because a final class never has any subclasses, the methods of a final class are never overridden (§8.4.6.1).

- -

8.1.3 Superclasses and Subclasses

- -The optional extends clause in a class declaration specifies the direct superclass -of the current class. A class is said to be a direct subclass of the class it extends. -The direct superclass is the class from whose implementation the implementation -of the current class is derived. The extends clause must not appear in the definition -of the class java.lang.Object (§20.1), because it is the primordial class -and has no direct superclass. If the class declaration for any other class has no -extends clause, then the class has the class java.lang.Object as its implicit -direct superclass. -

-The following is repeated from §4.3 to make the presentation here clearer: -

-The ClassType must name an accessible (§6.6) class type, or a compile-time error occurs. All classes in the current package are accessible. Classes in other packages are accessible if the host system permits access to the package (§7.2) and the class is declared public. If the specified ClassType names a class that is final (§8.1.2.2), then a compile-time error occurs; final classes are not allowed to have subclasses.

- -In the example:

-


class Point { int x, y; } -

final class ColoredPoint extends Point { int color; } -
class Colored3DPoint extends ColoredPoint { int z; } // error -
-the relationships are as follows: -

-The declaration of class Colored3dPoint causes a compile-time error because it -attempts to extend the final class ColoredPoint. -

-The subclass relationship is the transitive closure of the direct subclass relationship. A class A is a subclass of class C if either of the following is true:

-

-Class C is said to be a superclass of class A whenever A is a subclass of C. -

-In the example:

-


class Point { int x, y; } -

class ColoredPoint extends Point { int color; } -
final class Colored3dPoint extends ColoredPoint { int z; } -
-the relationships are as follows: -

-A compile-time error occurs if a class is declared to be a subclass of itself. For -example: -


class Point extends ColoredPoint { int x, y; } -
class ColoredPoint extends Point { int color; } -
-causes a compile-time error. If circularly declared classes are detected at run time, -as classes are loaded (§12.2), then a ClassCircularityError is thrown. -

-

8.1.4 Superinterfaces

- -The optional implements clause in a class declaration lists the names of interfaces -that are direct superinterfaces of the class being declared: -

-The following is repeated from §4.3 to make the presentation here clearer: -

-Each InterfaceType must name an accessible (§6.6) interface type, or a compile- -time error occurs. All interfaces in the current package are accessible. Interfaces -in other packages are accessible if the host system permits access to the package -(§7.4.4) and the interface is declared public. -

-A compile-time error occurs if the same interface is mentioned two or more times in a single implements clause, even if the interface is named in different ways; for example, the code:

-


-class Redundant implements java.lang.Cloneable, Cloneable {
-	int x;
-}
-
-results in a compile-time error because the names java.lang.Cloneable and -Cloneable refer to the same interface. -

-An interface type I is a superinterface of class type C if any of the following is true:

-

-A class is said to implement all its superinterfaces. -

-In the example:

-


-public interface Colorable {
-	void setColor(int color);
-	int getColor();
-}
-
-public interface Paintable extends Colorable { - int MATTE = 0, GLOSSY = 1; - void setFinish(int finish); - int getFinish(); -} -

class Point { int x, y; } -
-class ColoredPoint extends Point implements Colorable { - int color; - public void setColor(int color) { this.color = color; } - public int getColor() { return color; } -} -
-class PaintedPoint extends ColoredPoint implements Paintable
-{ - int finish; - public void setFinish(int finish) { - this.finish = finish; - } - public int getFinish() { return finish; } -} -
-the relationships are as follows: -

-A class can have a superinterface in more than one way. In this example, the class -PaintedPoint has Colorable as a superinterface both because it is a superinterface -of ColoredPoint and because it is a superinterface of Paintable. -

-Unless the class being declared is abstract, the declarations of the methods defined in each direct superinterface must be implemented either by a declaration in this class or by an existing method declaration inherited from the direct superclass, because a class that is not abstract is not permitted to have abstract methods (§8.1.2.1).

- -Thus, the example:

-


-interface Colorable {
-	void setColor(int color);
-	int getColor();
-}
-

class Point { int x, y; }; -
-class ColoredPoint extends Point implements Colorable { - int color; -} -
-causes a compile-time error, because ColoredPoint is not an abstract class but -it fails to provide an implementation of methods setColor and getColor of the -interface Colorable. -

-It is permitted for a single method declaration in a class to implement methods of more than one superinterface. For example, in the code:

-


interface Fish { int getNumberOfScales(); } -

interface Piano { int getNumberOfScales(); } -

-class Tuna implements Fish, Piano {
-	// You can tune a piano, but can you tuna fish?
-	int getNumberOfScales() { return 91; }
-}
-
-the method getNumberOfScales in class Tuna has a name, signature, and return -type that matches the method declared in interface Fish and also matches the -method declared in interface Piano; it is considered to implement both. -

-On the other hand, in a situation such as this:

-


interface Fish { int getNumberOfScales(); } -

interface StringBass { double getNumberOfScales(); } -

-class Bass implements Fish, StringBass {
-	// This declaration cannot be correct, no matter what type is used.
-	public ??? getNumberOfScales() { return 91; }
-}
-
-it is impossible to declare a method named getNumberOfScales with the same -signature and return type as those of both the methods declared in interface Fish -and in interface StringBass, because a class can have only one method with a -given signature (§8.4). Therefore, it is impossible for a single class to implement -both interface Fish and interface StringBass (§8.4.6). -

-

8.1.5 Class Body and Member Declarations

- -A class body may contain declarations of members of the class, that is, fields -(§8.3) and methods (§8.4). A class body may also contain static initializers (§8.5) -and declarations of constructors (§8.6) for the class. -

-The scope of the name of a member declared in or inherited by a class type is the -entire body of the class type declaration. -

-

8.2 Class Members

- -The members of a class type are all of the following: -

-Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

- -Constructors and static initializers are not members and therefore are not inherited.

- -The example:

-


-class Point {
-	int x, y;
-	private Point() { reset(); }
-	Point(int x, int y) { this.x = x; this.y = y; }
-	private void reset() { this.x = 0; this.y = 0; }
-}
-
-class ColoredPoint extends Point { - int color; - void clear() { reset(); } // error -} -
-class Test { - public static void main(String[] args) { - ColoredPoint c = new ColoredPoint(0, 0); // error - c.reset(); // error - } -} -
-causes four compile-time errors: -

-

8.2.1 Examples of Inheritance

- -This section illustrates inheritance of class members through several examples. -

-

8.2.1.1 Example: Inheritance with Default Access

- -Consider the example where the points package declares two compilation units: -


package points; -

-public class Point {
-	int x, y;
- public void move(int dx, int dy) { x += dx; y += dy; } -} -
-and: -


package points; -

-public class Point3d extends Point {
-	int z;
-	public void move(int dx, int dy, int dz) {
-		x += dx; y += dy; z += dz;
-	}
-}
-
-and a third compilation unit, in another package, is: -


import points.Point3d; -

-class Point4d extends Point3d {
-	int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		x += dx; y += dy; z += dz; w += dw; // compile-time errors
-	}
-}
-
-Here both classes in the points package compile. The class Point3d inherits the -fields x and y of class Point, because it is in the same package as Point. The -class Point4d, which is in a different package, does not inherit the fields x and y -of class Point or the field z of class Point3d, and so fails to compile. -

-A better way to write the third compilation unit would be:

-


import points.Point3d; -

-class Point4d extends Point3d {
-	int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		super.move(dx, dy, dz); w += dw;
-	}
-}
-
-using the move method of the superclass Point3d to process dx, dy, and dz. If -Point4d is written in this way it will compile without errors. -

-

8.2.1.2 Inheritance with public and protected

- -Given the class Point: -


package points; -

-public class Point {
-
public int x, y; -

protected int useCount = 0; -

static protected int totalUseCount = 0; -
- public void move(int dx, int dy) { - x += dx; y += dy; useCount++; totalUseCount++; - } -
} -
-the public and protected fields x, y, useCount and totalUseCount are inherited -in all subclasses of Point. Therefore, this test program, in another package, -can be compiled successfully: -


-class Test extends points.Point {
-	public void moveBack(int dx, int dy) {
-		x -= dx; y -= dy; useCount++; totalUseCount++;
-	}
-}
-
-

8.2.1.3 Inheritance with private

- -In the example: -


-class Point {
-
int x, y; -
- void move(int dx, int dy) { - x += dx; y += dy; totalMoves++; - } -

private static int totalMoves; -

void printMoves() { System.out.println(totalMoves); } -
} -
-class Point3d extends Point { -
int z; -
- void move(int dx, int dy, int dz) { - super.move(dx, dy); z += dz; totalMoves++; - } -
} -
-the class variable totalMoves can be used only within the class Point; it is not -inherited by the subclass Point3d. A compile-time error occurs at the point where -method move of class Point3d tries to increment totalMoves. -

-

8.2.1.4 Accessing Members of Inaccessible Classes

- -Even though a class might not be declared public, instances of the class might be -available at run time to code outside the package in which it is declared if it has a -public superclass or superinterface. An instance of the class can be assigned to a -variable of such a public type. An invocation of a public method of the object -referred to by such a variable may invoke a method of the class if it implements or -overrides a method of the public superclass or superinterface. (In this situation, -the method is necessarily declared public, even though it is declared in a class -that is not public.) -

-Consider the compilation unit:

-


package points; -

-public class Point {
-	public int x, y;
-	public void move(int dx, int dy) {
-		x += dx; y += dy;
-	}
-}
-
-and another compilation unit of another package: -


package morePoints; -

-class Point3d extends points.Point {
-	public int z;
-	public void move(int dx, int dy, int dz) {
-		super.move(dx, dy); z += dz;
-	}
-}
-
-public class OnePoint { - static points.Point getOne() { return new Point3d(); } -} -
-An invocation morePoints.OnePoint.getOne() in yet a third package would -return a Point3d that can be used as a Point, even though the type Point3d is -not available outside the package morePoints. The method move could then be -invoked for that object, which is permissible because method move of Point3d is -public (as it must be, for any method that overrides a public method must itself -be public, precisely so that situations such as this will work out correctly). The -fields x and y of that object could also be accessed from such a third package. -

-While the field z of class Point3d is public, it is not possible to access this field from code outside the package morePoints, given only a reference to an instance of class Point3d in a variable p of type Point. This is because the expression p.z is not correct, as p has type Point and class Point has no field named z; also, the expression ((Point3d)p).z is not correct, because the class type Point3d cannot be referred to outside package morePoints. The declaration of the field z as public is not useless, however. If there were to be, in package morePoints, a public subclass Point4d of the class Point3d:

-


package morePoints; -

-public class Point4d extends Point3d {
-	public int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		super.move(dx, dy, dz); w += dw;
-	}
-}
-
-then class Point4d would inherit the field z, which, being public, could then be -accessed by code in packages other than morePoints, through variables and -expressions of the public type Point4d. -

-

8.3 Field Declarations

- -The variables of a class type are introduced by field declarations: -

-The FieldModifiers are described in §8.3.1. The Identifier in a FieldDeclarator -may be used in a name to refer to the field. The name of a field has as its scope -(§6.3) the entire body of the class declaration in which it is declared. More than -one field may be declared in a single field declaration by using more than one -declarator; the FieldModifiers and Type apply to all the declarators in the declaration. -Variable declarations involving array types are discussed in §10.2. -

-It is a compile-time error for the body of a class declaration to contain declarations of two fields with the same name. Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (§6.5).

- -If the class declares a field with a certain name, then the declaration of that field is said to hide (§6.3.1) any and all accessible declarations of fields with the same name in the superclasses and superinterfaces of the class.

- -If a field declaration hides the declaration of another field, the two fields need not have the same type.

- -A class inherits from its direct superclass and direct superinterfaces all the fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

- -It is possible for a class to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.

- -There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.

- -A hidden field can be accessed by using a qualified name (if it is static) or by using a field access expression (§15.10) that contains the keyword super or a cast to a superclass type. See §15.10.2 for discussion and an example.

- -

8.3.1 Field Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. A -compile-time error occurs if the same modifier appears more than once in a field -declaration, or if a field declaration has more than one of the access modifiers -public, protected, and private. If two or more (distinct) field modifiers -appear in a field declaration, it is customary, though not required, that they appear -in the order consistent with that shown above in the production for FieldModifier. -

-

8.3.1.1 static Fields

- -If a field is declared static, there exists exactly one incarnation of the field, no -matter how many instances (possibly zero) of the class may eventually be created. -A static field, sometimes called a class variable, is incarnated when the class is -initialized (§12.4). -

-A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.

- -The example program:

-


-class Point {
-	int x, y, useCount;
-	Point(int x, int y) { this.x = x; this.y = y; }
-	final static Point origin = new Point(0, 0);
-}
-
-class Test { - public static void main(String[] args) { - Point p = new Point(1,1); - Point q = new Point(2,2); - p.x = 3; p.y = 3; p.useCount++; p.origin.useCount++; - System.out.println("(" + q.x + "," + q.y + ")"); - System.out.println(q.useCount); - System.out.println(q.origin == Point.origin); - System.out.println(q.origin.useCount); - } -} -
-prints: -


-(2,2)
-0
-true
-1
-
-showing that changing the fields x, y, and useCount of p does not affect the fields -of q, because these fields are instance variables in distinct objects. In this example, -the class variable origin of the class Point is referenced both using the class -name as a qualifier, in Point.origin, and using variables of the class type in -field access expressions (§15.10), as in p.origin and q.origin. These two ways -of accessing the origin class variable access the same object, evidenced by the -fact that the value of the reference equality expression (§15.20.3): -

q.origin==Point.origin
-
-is true. Further evidence is that the incrementation: -

p.origin.useCount++;
-
-causes the value of q.origin.useCount to be 1; this is so because p.origin and -q.origin refer to the same variable. -

-

8.3.1.2 final Fields

- -A field can be declared final, in which case its declarator must include a variable -initializer or a compile-time error occurs. Both class and instance variables -(static and non-static fields) may be declared final. -

-Any attempt to assign to a final field results in a compile-time error. Therefore, once a final field has been initialized, it always contains the same value. If a final field holds a reference to an object, then the state of the object may be changed by operations on the object, but the field will always refer to the same object. This applies also to arrays, because arrays are objects; if a final field holds a reference to an array, then the components of the array may be changed by operations on the array, but the field will always refer to the same array.

- -Declaring a field final can serve as useful documentation that its value will not change, can help to avoid programming errors, and can make it easier for a compiler to generate efficient code.

- -In the example:

-


-class Point {
-	int x, y;
-	int useCount;
-	Point(int x, int y) { this.x = x; this.y = y; }
-	final static Point origin = new Point(0, 0);
-}
-
-the class Point declares a final class variable origin. The origin variable -holds a reference to an object that is an instance of class Point whose coordinates -are (0, 0). The value of the variable Point.origin can never change, so it always -refers to the same Point object, the one created by its initializer. However, an -operation on this Point object might change its state-for example, modifying its -useCount or even, misleadingly, its x or y coordinate. -

-

8.3.1.3 transient Fields

- -Variables may be marked transient to indicate that they are not part of the persistent -state of an object. If an instance of the class Point: -


-class Point {
-	int x, y;
-	transient float rho, theta;
-}
-
-were saved to persistent storage by a system service, then only the fields x and y -would be saved. This specification does not yet specify details of such services; -we intend to provide them in a future version of this specification. -

-

8.3.1.4 volatile Fields

- -As described in §17, the Java language allows threads that access shared variables -to keep private working copies of the variables; this allows a more efficient implementation -of multiple threads. These working copies need be reconciled with the -master copies in the shared main memory only at prescribed synchronization -points, namely when objects are locked or unlocked. As a rule, to ensure that -shared variables are consistently and reliably updated, a thread should ensure that -it has exclusive use of such variables by obtaining a lock that, conventionally, -enforces mutual exclusion for those shared variables. -

-Java provides a second mechanism that is more convenient for some purposes: a field may be declared volatile, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.

- -If, in the following example, one thread repeatedly calls the method one (but no more than Integer.MAX_VALUE (§20.7.2) times in all), and another thread repeatedly calls the method two:

-


-class Test {
-
static int i = 0, j = 0; -
- static void one() { i++; j++; } - - static void two() { - System.out.println("i=" + i + " j=" + j); - } -
} -
-then method two could occasionally print a value for j that is greater than the -value of i, because the example includes no synchronization and, under the rules -explained in §17, the shared values of i and j might be updated out of order. -

-One way to prevent this out-or-order behavior would be to declare methods one and two to be synchronized (§8.4.3.5):

-


-class Test {
-
static int i = 0, j = 0; -
- static synchronized void one() { i++; j++; } - - static synchronized void two() { - System.out.println("i=" + i + " j=" + j); - } -
} -
-This prevents method one and method two from being executed concurrently, and -furthermore guarantees that the shared values of i and j are both updated before -method one returns. Therefore method two never observes a value for j greater -than that for i; indeed, it always observes the same value for i and j. -

-Another approach would be to declare i and j to be volatile:

-


-class Test {
-
static volatile int i = 0, j = 0; -
- static void one() { i++; j++; } - - static void two() { - System.out.println("i=" + i + " j=" + j); - } -
} -
-This allows method one and method two to be executed concurrently, but guarantees -that accesses to the shared values for i and j occur exactly as many times, -and in exactly the same order, as they appear to occur during execution of the program -text by each thread. Therefore, method two never observes a value for j -greater than that for i, because each update to i must be reflected in the shared -value for i before the update to j occurs. It is possible, however, that any given -invocation of method two might observe a value for j that is much greater than the -value observed for i, because method one might be executed many times between -the moment when method two fetches the value of i and the moment when -method two fetches the value of j. -

-See §17 for more discussion and examples.

- -A compile-time error occurs if a final variable is also declared volatile.

- -

8.3.2 Initialization of Fields

- -If a field declarator contains a variable initializer, then it has the semantics of an -assignment (§15.25) to the declared variable, and: -

-The example:

-


-class Point {
-	int x = 1, y = 5;
-}
-
class Test { - public static void main(String[] args) { - Point p = new Point(); - System.out.println(p.x + ", " + p.y); - } -} -
-produces the output: -

1, 5
-
-because the assignments to x and y occur whenever a new Point is created. -

-Variable initializers are also used in local variable declaration statements (§14.3), where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.

- -It is a compile-time error if the evaluation of a variable initializer for a field of a class (or interface) can complete abruptly with a checked exception (§11.2).

- -

8.3.2.1 Initializers for Class Variables

- -A compile-time error occurs if an initialization expression for a class variable contains -a use by a simple name of that class variable or of another class variable -whose declaration occurs to its right (that is, textually later) in the same class. -Thus: -


-class Test {
-	static float f = j;							// compile-time error: forward reference
-	static int j = 1;
-	static int k = k+1;							// compile-time error: forward reference
-}
-
-causes two compile-time errors, because j is referred to in the initialization of f -before j is declared and because the initialization of k refers to k itself. -

-If a reference by simple name to any instance variable occurs in an initialization expression for a class variable, then a compile-time error occurs.

- -If the keyword this (§15.7.2) or the keyword super (§15.10.2, §15.11) occurs in an initialization expression for a class variable, then a compile-time error occurs.

- -(One subtlety here is that, at run time, static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (§9.3.1). These variables are "constants" that will never be observed to have their default initial values (§4.5.4), even by devious programs. See §12.4.2 and §13.4.8 for more discussion.)

- -

8.3.2.2 Initializers for Instance Variables

- -A compile-time error occurs if an initialization expression for an instance variable -contains a use by a simple name of that instance variable or of another instance -variable whose declaration occurs to its right (that is, textually later) in the same -class. Thus: -


-class Test {
-	float f = j;
-	int j = 1;
-	int k = k+1;
-}
-
-causes two compile-time errors, because j is referred to in the initialization of f -before j is declared and because the initialization of k refers to k itself. -

-Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later. Thus the example:

-


-class Test {
-	float f = j;
-	static int j = 1;
-}
-
-compiles without error; it initializes j to 1 when class Test is initialized, and initializes -f to the current value of j every time an instance of class Test is created. -

-Initialization expressions for instance variables are permitted to refer to the current object this (§15.7.2) and to use the keyword super (§15.10.2, §15.11).

- -

8.3.3 Examples of Field Declarations

- -The following examples illustrate some (possibly subtle) points about field declarations. - -

-

8.3.3.1 Example: Hiding of Class Variables

- -The example: -


-class Point {
-	static int x = 2;
-}
-
-class Test extends Point { - static double x = 4.7; - public static void main(String[] args) {
- new Test().printX(); - } - void printX() { - System.out.println(x + " " + super.x); - } -} -
-produces the output: -

4.7 2
-
-because the declaration of x in class Test hides the definition of x in class Point, -so class Test does not inherit the field x from its superclass Point. Within the -declaration of class Test, the simple name x refers to the field declared within -class Test. Code in class Test may refer to the field x of class Point as super.x -(or, because x is static, as Point.x). If the declaration of Test.x is deleted: -


-class Point {
-	static int x = 2;
-}
-
-class Test extends Point { - public static void main(String[] args) { - new Test().printX(); - } - void printX() { - System.out.println(x + " " + super.x); - } -} -
-then the field x of class Point is no longer hidden within class Test; instead, the -simple name x now refers to the field Point.x. Code in class Test may still refer -to that same field as super.x. Therefore, the output from this variant program is: -

2 2
-
-

8.3.3.2 Example: Hiding of Instance Variables

- -This example is similar to that in the previous section, but uses instance variables -rather than static variables. The code: -


-class Point {
-	int x = 2;
-}
-
-class Test extends Point { - double x = 4.7; - void printBoth() { - System.out.println(x + " " + super.x); - } - public static void main(String[] args) { - Test sample = new Test(); - sample.printBoth(); - System.out.println(sample.x + " " +
- ((Point)sample).x); - } -} -
-produces the output: -


-4.7 2
-4.7 2
-
-because the declaration of x in class Test hides the definition of x in class Point, -so class Test does not inherit the field x from its superclass Point. It must be -noted, however, that while the field x of class Point is not inherited by class -Test, it is nevertheless implemented by instances of class Test. In other words, -every instance of class Test contains two fields, one of type int and one of type -float. Both fields bear the name x, but within the declaration of class Test, the -simple name x always refers to the field declared within class Test. Code in -instance methods of class Test may refer to the instance variable x of class Point -as super.x. -

-Code that uses a field access expression to access field x will access the field named x in the class indicated by the type of reference expression. Thus, the expression sample.x accesses a float value, the instance variable declared in class Test, because the type of the variable sample is Test, but the expression ((Point)sample).x accesses an int value, the instance variable declared in class Point, because of the cast to type Point.

- -If the declaration of x is deleted from class Test, as in the program:

-


-class Point {
-	static int x = 2;
-}
-
-class Test extends Point { - void printBoth() { - System.out.println(x + " " + super.x); - } - public static void main(String[] args) { - Test sample = new Test(); - sample.printBoth(); - System.out.println(sample.x + " " +
- ((Point)sample).x); - } -} -
-then the field x of class Point is no longer hidden within class Test. Within -instance methods in the declaration of class Test, the simple name x now refers to -the field declared within class Point. Code in class Test may still refer to that -same field as super.x. The expression sample.x still refers to the field x within -type Test, but that field is now an inherited field, and so refers to the field x -declared in class Point. The output from this variant program is: -


-2 2
-2 2
-
-

8.3.3.3 Example: Multiply Inherited Fields

- -A class may inherit two or more fields with the same name, either from two interfaces -or from its superclass and an interface. A compile-time error occurs on any -attempt to refer to any ambiguously inherited field by its simple name. A qualified -name or a field access expression that contains the keyword super (§15.10.2) may -be used to access such fields unambiguously. In the example: -


interface Frob { float v = 2.0f; } -

class SuperTest { int v = 3; } -

-class Test extends SuperTest implements Frob {
-	public static void main(String[] args) {
-		new Test().printV();
-	}
-	void printV() { System.out.println(v); }
-}
-
-the class Test inherits two fields named v, one from its superclass SuperTest and -one from its superinterface Frob. This in itself is permitted, but a compile-time -error occurs because of the use of the simple name v in method printV: it cannot -be determined which v is intended. -

-The following variation uses the field access expression super.v to refer to the field named v declared in class SuperTest and uses the qualified name Frob.v to refer to the field named v declared in interface Frob:

-


interface Frob { float v = 2.0f; } -

class SuperTest { int v = 3; } -

-class Test extends SuperTest implements Frob {
-	public static void main(String[] args) {
-		new Test().printV();
-	}
-	void printV() {
-		System.out.println((super.v + Frob.v)/2);
-	}
-}
-
-It compiles and prints: -

2.5
-
-Even if two distinct inherited fields have the same type, the same value, and are both final, any reference to either field by simple name is considered ambiguous and results in a compile-time error. In the example:

-


interface Color { int RED=0, GREEN=1, BLUE=2; } -

interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; } -

-class Test implements Color, TrafficLight {
-	public static void main(String[] args) {
-		System.out.println(GREEN);										// compile-time error
-		System.out.println(RED);										// compile-time error
-	}
-}
-
-it is not astonishing that the reference to GREEN should be considered ambiguous, -because class Test inherits two different declarations for GREEN with different -values. The point of this example is that the reference to RED is also considered -ambiguous, because two distinct declarations are inherited. The fact that the two -fields named RED happen to have the same type and the same unchanging value -does not affect this judgment. -

-

8.3.3.4 Example: Re-inheritance of Fields

- -If the same field declaration is inherited from an interface by multiple paths, the -field is considered to be inherited only once. It may be referred to by its simple -name without ambiguity. For example, in the code: -


-public interface Colorable {
-	int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff;
-}
-
-public interface Paintable extends Colorable { - int MATTE = 0, GLOSSY = 1; -} -

class Point { int x, y; } -
-class ColoredPoint extends Point implements Colorable { - . . . -} -
-class PaintedPoint extends ColoredPoint implements Paintable -{ - . . . RED . . . -} -
-the fields RED, GREEN, and BLUE are inherited by the class PaintedPoint both -through its direct superclass ColoredPoint and through its direct superinterface -Paintable. The simple names RED, GREEN, and BLUE may nevertheless be used -without ambiguity within the class PaintedPoint to refer to the fields declared in -interface Colorable. -

-

8.4 Method Declarations

- -A method declares executable code that can be invoked, passing a fixed number of -values as arguments. -

-The MethodModifiers are described in §8.4.3, the Throws clause in §8.4.4, and the -MethodBody in §8.4.5. A method declaration either specifies the type of value that -the method returns or uses the keyword void to indicate that the method does not -return a value. -

-The Identifier in a MethodDeclarator may be used in a name to refer to the method. A class can declare a method with the same name as the class or a field of the class.

- -For compatibility with older versions of Java, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. This is supported by the obsolescent production:

-

-but should not be used in new Java code. -

-It is a compile-time error for the body of a class to have as members two methods with the same signature (§8.4.2) (name, number of parameters, and types of any parameters). Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (§6.5).

- -

8.4.1 Formal Parameters

- -The formal parameters of a method, if any, are specified by a list of comma-separated -parameter specifiers. Each parameter specifier consists of a type and an identifier -(optionally followed by brackets) that specifies the name of the parameter: -

-The following is repeated from §8.3 to make the presentation here clearer: -

-If a method has no parameters, only an empty pair of parentheses appears in the method's declaration.

- -If two formal parameters are declared to have the same name (that is, their declarations mention the same Identifier), then a compile-time error occurs.

- -When the method is invoked (§15.11), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method to refer to the formal parameter.

- -The scope of formal parameter names is the entire body of the method. These parameter names may not be redeclared as local variables or exception parameters within the method; that is, hiding the name of a parameter is not permitted.

- -Formal parameters are referred to only using simple names, never by using qualified names (§6.6).

- -

8.4.2 Method Signature

- -The signature of a method consists of the name of the method and the number and -types of formal parameters to the method. A class may not declare two methods -with the same signature, or a compile-time error occurs. The example: -


-class Point implements Move {
-	int x, y;
-	abstract void move(int dx, int dy);
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-causes a compile-time error because it declares two move methods with the same -signature. This is an error even though one of the declarations is abstract. -

-

8.4.3 Method Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. -A compile-time error occurs if the same modifier appears more than once in a -method declaration, or if a method declaration has more than one of the access -modifiers public, protected, and private. A compile-time error occurs if a -method declaration that contains the keyword abstract also contains any one of -the keywords private, static, final, native, or synchronized. -

-If two or more method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier.

- -

8.4.3.1 abstract Methods

- -An abstract method declaration introduces the method as a member, providing -its signature (name and number and type of parameters), return type, and throws -clause (if any), but does not provide an implementation. The declaration of an -abstract method m must appear within an abstract class (call it A); otherwise a -compile-time error results. Every subclass of A that is not abstract must provide -an implementation for m, or a compile-time error occurs. More precisely, for every -subclass C of the abstract class A, if C is not abstract, then there must be some -class B such that all of the following are true: -

-If there is no such class B, then a compile-time error occurs. -

-It is a compile-time error for a private method to be declared abstract. It would be impossible for a subclass to implement a private abstract method, because private methods are not visible to subclasses; therefore such a method could never be used.

- -It is a compile-time error for a static method to be declared abstract.

- -It is a compile-time error for a final method to be declared abstract.

- -An abstract class can override an abstract method by providing another abstract method declaration. This can provide a place to put a documentation comment (§18), or to declare that the set of checked exceptions (§11.2) that can be thrown by that method, when it is implemented by its subclasses, is to be more limited. For example, consider this code:

-


-class BufferEmpty extends Exception {
-	BufferEmpty() { super(); }
-	BufferEmpty(String s) { super(s); }
-}
-
-class BufferError extends Exception { - BufferError() { super(); } - BufferError(String s) { super(s); } -} -
-public interface Buffer { - char get() throws BufferEmpty, BufferError; -} -
-public abstract class InfiniteBuffer implements Buffer { - abstract char get() throws BufferError; -} -
-The overriding declaration of method get in class InfiniteBuffer states that -method get in any subclass of InfiniteBuffer never throws a BufferEmpty -exception, putatively because it generates the data in the buffer, and thus can never -run out of data. -

-An instance method that is not abstract can be overridden by an abstract method. For example, we can declare an abstract class Point that requires its subclasses to implement toString if they are to be complete, instantiable classes:

-


-abstract class Point {
-	int x, y;
-	public abstract String toString();
-}
-
-This abstract declaration of toString overrides the non-abstract toString -method of class Object (§20.1.2). (Class Object is the implicit direct superclass -of class Point.) Adding the code: -


-class ColoredPoint extends Point {
-	int color;
-	public String toString() {
-		return super.toString() + ": color " + color; // error
-	}
-}
-
-results in a compile-time error because the invocation super.toString() refers -to method toString in class Point, which is abstract and therefore cannot be -invoked. Method toString of class Object can be made available to class -ColoredPoint only if class Point explicitly makes it available through some -other method, as in: -


-abstract class Point {
-	int x, y;
-	public abstract String toString();
-	protected String objString() { return super.toString(); }
-}
-
-class ColoredPoint extends Point {
-	int color;
-	public String toString() {
-		return objString() + ": color " + color;														// correct
-	}
-}
-
-

8.4.3.2 static Methods

- -A method that is declared static is called a class method. A class method is -always invoked without reference to a particular object. An attempt to reference -the current object using the keyword this or the keyword super in the body of a -class method results in a compile time error. It is a compile-time error for a -static method to be declared abstract. -

-A method that is not declared static is called an instance method, and sometimes called a non-static method). An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

- -

8.4.3.3 final Methods

- -A method can be declared final to prevent subclasses from overriding or hiding -it. It is a compile-time error to attempt to override or hide a final method. -

-A private method and all methods declared in a final class (§8.1.2.2) are implicitly final, because it is impossible to override them. It is permitted but not required for the declarations of such methods to redundantly include the final keyword.

- -It is a compile-time error for a final method to be declared abstract.

- -At run-time, a machine-code generator or optimizer can easily and safely "inline" the body of a final method, replacing an invocation of the method with the code in its body, as in the example:

-


-final class Point {
-	int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-class Test { - public static void main(String[] args) { - Point[] p = new Point[100]; - for (int i = 0; i < p.length; i++) { - p[i] = new Point(); - p[i].move(i, p.length-1-i); - } - } -} -
-Here, inlining the method move of class Point in method main would transform -the for loop to the form: -


-		for (int i = 0; i < p.length; i++) {
-			p[i] = new Point();
-			Point pi = p[i];
-			pi.x += i;
-			pi.y += p.length-1-i;
-		}
-
-The loop might then be subject to further optimizations. -

-Such inlining cannot be done at compile time unless it can be guaranteed that Test and Point will always be recompiled together, so that whenever Point-and specifically its move method-changes, the code for Test.main will also be updated.

- -

8.4.3.4 native Methods

- -A method that is native is implemented in platform-dependent code, typically -written in another programming language such as C, C++, FORTRAN, or assembly -language. The body of a native method is given as a semicolon only, indicating -that the implementation is omitted, instead of a block. -

-A compile-time error occurs if a native method is declared abstract.

- -For example, the class RandomAccessFile of the standard package java.io might declare the following native methods:

-


package java.io; -

-public class RandomAccessFile
- implements DataOutput, DataInput -{ . . . - public native void open(String name, boolean writeable) - throws IOException; - public native int readBytes(byte[] b, int off, int len) - throws IOException; - public native void writeBytes(byte[] b, int off, int len) - throws IOException; - public native long getFilePointer() throws IOException; - public native void seek(long pos) throws IOException; - public native long length() throws IOException; - public native void close() throws IOException; -} -
-

8.4.3.5 synchronized Methods

- -A synchronized method acquires a lock (§17.1) before it executes. For a class -(static) method, the lock associated with the Class object (§20.3) for the -method's class is used. For an instance method, the lock associated with this (the -object for which the method was invoked) is used. These are the same locks that -can be used by the synchronized statement (§14.17); thus, the code: -


-class Test {
-	int count;
-	synchronized void bump() { count++; }
-	static int classCount;
-	static synchronized void classBump() {
-		classCount++;
-	}
-}
-
-has exactly the same effect as: -


-class BumpTest {
-	int count;
-	void bump() {
-		synchronized (this) {
-			count++;
-		}
-	}
-	static int classCount;
-	static void classBump() {
-		try {
-			synchronized (Class.forName("BumpTest")) {
-				classCount++;
-			}
-		} catch (ClassNotFoundException e) {
-				...
-		}
-	}
-}
-
-The more elaborate example: -


-public class Box {
-
private Object boxContents; -
- public synchronized Object get() { - Object contents = boxContents; - boxContents = null; - return contents; - } -
- public synchronized boolean put(Object contents) { - if (boxContents != null) - return false; - boxContents = contents; - return true; - } -
} -
-defines a class which is designed for concurrent use. Each instance of the class -Box has an instance variable contents that can hold a reference to any object. -You can put an object in a Box by invoking put, which returns false if the box is -already full. You can get something out of a Box by invoking get, which returns a -null reference if the box is empty. -

-If put and get were not synchronized, and two threads were executing methods for the same instance of Box at the same time, then the code could misbehave. It might, for example, lose track of an object because two invocations to put occurred at the same time.

- -See §17 for more discussion of threads and locks.

- -

8.4.4 Method Throws

- -A throws clause is used to declare any checked exceptions (§11.2) that can result -from the execution of a method or constructor: -

-A compile-time error occurs if any ClassType mentioned in a throws clause is not -the class Throwable (§20.22) or a subclass of Throwable. It is permitted but not -required to mention other (unchecked) exceptions in a throws clause. -

-For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a throws clause in the declaration of the method or constructor.

- -The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a throws clause. Java thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.

- -The predefined exceptions that are not checked in this way are those for which declaring every possible occurrence would be unimaginably inconvenient:

-

-A method that overrides or hides another method (§8.4.6), including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.

- -More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. If n has a throws clause that mentions any checked exception types, then m must have a throws clause, and for every checked exception type listed in the throws clause of n, that same exception class or one of its superclasses must occur in the throws clause of m; otherwise, a compile-time error occurs.

- -See §11 for more information about exceptions and a large example.

- -

8.4.5 Method Body

- -A method body is either a block of code that implements the method or simply a -semicolon, indicating the lack of an implementation. The body of a method must -be a semicolon if and only if the method is either abstract (§8.4.3.1) or native -(§8.4.3.4). -

-A compile-time error occurs if a method declaration is either abstract or -native and has a block for its body. A compile-time error occurs if a method declaration -is neither abstract nor native and has a semicolon for its body. -

-If an implementation is to be provided for a method but the implementation requires no executable code, the method body should be written as a block that contains no statements: "{ }".

- -If a method is declared void, then its body must not contain any return statement (§14.15) that has an Expression.

- -If a method is declared to have a return type, then every return statement (§14.15) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.1). In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body."

- -Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:

-

class DizzyDean {
- int pitch() { throw new RuntimeException("90 mph?!"); }
-} -
-

8.4.6 Inheritance, Overriding, and Hiding

- -A class inherits from its direct superclass and direct superinterfaces all the methods -(whether abstract or not) of the superclass and superinterfaces that are -accessible to code in the class and are neither overridden (§8.4.6.1) nor hidden -(§8.4.6.2) by a declaration in the class. -

-

8.4.6.1 Overriding (By Instance Methods)

- -If a class declares an instance method, then the declaration of that method is said -to override any and all methods with the same signature in the superclasses and -superinterfaces of the class that would otherwise be accessible to code in the class. -Moreover, if the method declared in the class is not abstract, then the declaration -of that method is said to implement any and all declarations of abstract -methods with the same signature in the superclasses and superinterfaces of the -class that would otherwise be accessible to code in the class. -

-A compile-time error occurs if an instance method overrides a static method. In this respect, overriding of methods differs from hiding of fields (§8.3), for it is permissible for an instance variable to hide a static variable.

- -An overridden method can be accessed by using a method invocation expression (§15.11) that contains the keyword super. Note that a qualified name or a cast to a superclass type is not effective in attempting to access an overridden method; in this respect, overriding of methods differs from hiding of fields. See §15.11.4.10 for discussion and examples of this point.

- -

8.4.6.2 Hiding (By Class Methods)

- -If a class declares a static method, then the declaration of that method is said to -hide any and all methods with the same signature in the superclasses and superinterfaces -of the class that would otherwise be accessible to code in the class. A -compile-time error occurs if a static method hides an instance method. In this -respect, hiding of methods differs from hiding of fields (§8.3), for it is permissible -for a static variable to hide an instance variable. -

-A hidden method can be accessed by using a qualified name or by using a method invocation expression (§15.11) that contains the keyword super or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.

- -

8.4.6.3 Requirements in Overriding and Hiding

- -If a method declaration overrides or hides the declaration of another method, then -a compile-time error occurs if they have different return types or if one has a -return type and the other is void. Moreover, a method declaration must not have a -throws clause that conflicts (§8.4.4) with that of any method that it overrides or -hides; otherwise, a compile-time error occurs. In these respects, overriding of -methods differs from hiding of fields (§8.3), for it is permissible for a field to hide -a field of another type. -

-The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:

-

-Note that a private method is never accessible to subclasses and so cannot be -hidden or overridden in the technical sense of those terms. This means that a subclass -can declare a method with the same signature as a private method in one of -its superclasses, and there is no requirement that the return type or throws clause -of such a method bear any relationship to those of the private method in the -superclass. -

-

8.4.6.4 Inheriting Methods with the Same Signature

- -It is possible for a class to inherit more than one method with the same signature -(§8.4.6.4). Such a situation does not in itself cause a compile-time error. There are -then two possible cases: -

-It is not possible for two or more inherited methods with the same signature not to -be abstract, because methods that are not abstract are inherited only from the -direct superclass, not from superinterfaces. -

-There might be several paths by which the same method declaration might be inherited from an interface. This fact causes no difficulty and never, of itself, results in a compile-time error.

- -

8.4.7 Overloading

- -If two methods of a class (whether both declared in the same class, or both inherited -by a class, or one declared and one inherited) have the same name but different -signatures, then the method name is said to be overloaded. This fact causes no -difficulty and never of itself results in a compile-time error. There is no required -relationship between the return types or between the throws clauses of two methods -with the same name but different signatures. -

-Methods are overridden on a signature-by-signature basis. If, for example, a class declares two public methods with the same name, and a subclass overrides one of them, the subclass still inherits the other method. In this respect, Java differs from C++.

- -When a method is invoked (§15.11), the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.11.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.11.4).

- -

8.4.8 Examples of Method Declarations

- -The following examples illustrate some (possibly subtle) points about method -declarations. -

-

8.4.8.1 Example: Overriding

- -In the example: -


-class Point {
-
int x = 0, y = 0; -

void move(int dx, int dy) { x += dx; y += dy; } -
} -
-class SlowPoint extends Point { -
int xLimit, yLimit; -
- void move(int dx, int dy) { - super.move(limit(dx, xLimit), limit(dy, yLimit)); - } -
- static int limit(int d, int limit) { - return d > limit ? limit : d < -limit ? -limit : d; - } -
} -
-the class SlowPoint overrides the declarations of method move of class Point -with its own move method, which limits the distance that the point can move on -each invocation of the method. When the move method is invoked for an instance -of class SlowPoint, the overriding definition in class SlowPoint will always be -called, even if the reference to the SlowPoint object is taken from a variable -whose type is Point. -

-

8.4.8.2 Example: Overloading, Overriding, and Hiding

- -In the example: -


-class Point {
-
int x = 0, y = 0; -

void move(int dx, int dy) { x += dx; y += dy; } -

int color; -
} -
-class RealPoint extends Point { -
float x = 0.0f, y = 0.0f; -

void move(int dx, int dy) { move((float)dx, (float)dy); } -

void move(float dx, float dy) { x += dx; y += dy; } -
} -
-the class RealPoint hides the declarations of the int instance variables x and y -of class Point with its own float instance variables x and y, and overrides the -method move of class Point with its own move method. It also overloads the name -move with another method with a different signature (§8.4.2). -

-In this example, the members of the class RealPoint include the instance variable color inherited from the class Point, the float instance variables x and y declared in RealPoint, and the two move methods declared in RealPoint.

- -Which of these overloaded move methods of class RealPoint will be chosen for any particular method invocation will be determined at compile time by the overloading resolution procedure described in §15.11.

- -

8.4.8.3 Example: Incorrect Overriding

- -This example is an extended variation of that in the preceding section: -


-class Point {
-
int x = 0, y = 0, color; -

void move(int dx, int dy) { x += dx; y += dy; } -

int getX() { return x; } -

int getY() { return y; } -
} -
-class RealPoint extends Point { -
float x = 0.0f, y = 0.0f; -

void move(int dx, int dy) { move((float)dx, (float)dy); } -

void move(float dx, float dy) { x += dx; y += dy; } -

float getX() { return x; } -

float getY() { return y; } -
} -
-Here the class Point provides methods getX and getY that return the values of its -fields x and y; the class RealPoint then overrides these methods by declaring -methods with the same signature. The result is two errors at compile time, one for -each method, because the return types do not match; the methods in class Point -return values of type int, but the wanna-be overriding methods in class -RealPoint return values of type float. -

-

8.4.8.4 Example: Overriding versus Hiding

- -This example corrects the errors of the example in the preceding section: -


-class Point {
-
int x = 0, y = 0; -

void move(int dx, int dy) { x += dx; y += dy; } -

int getX() { return x; } -

int getY() { return y; } -

int color; -
} -
-class RealPoint extends Point { -
float x = 0.0f, y = 0.0f; -

void move(int dx, int dy) { move((float)dx, (float)dy); } -

void move(float dx, float dy) { x += dx; y += dy; } -

int getX() { return (int)Math.floor(x); } -

int getY() { return (int)Math.floor(y); } -
} -
-Here the overriding methods getX and getY in class RealPoint have the same -return types as the methods of class Point that they override, so this code can be -successfully compiled. -

-Consider, then, this test program:

-


-class Test {
-
-	public static void main(String[] args) {
-		RealPoint rp = new RealPoint();
-		Point p = rp;
-		rp.move(1.71828f, 4.14159f);
-		p.move(1, -1);
-		show(p.x, p.y);
-		show(rp.x, rp.y);
-		show(p.getX(), p.getY());
-		show(rp.getX(), rp.getY());
-	}
-
- static void show(int x, int y) { - System.out.println("(" + x + ", " + y + ")"); - } -
- static void show(float x, float y) { - System.out.println("(" + x + ", " + y + ")"); - } -
} -
-The output from this program is: -


-(0, 0)
-(2.7182798, 3.14159)
-(2, 3)
-(2, 3)
-
-The first line of output illustrates the fact that an instance of RealPoint actually contains the two integer fields declared in class Point; it is just that their names are hidden from code that occurs within the declaration of class RealPoint (and those of any subclasses it might have). When a reference to an instance of class RealPoint in a variable of type Point is used to access the field x, the integer field x declared in class Point is accessed. The fact that its value is zero indicates that the method invocation p.move(1, -1) did not invoke the method move of class Point; instead, it invoked the overriding method move of class RealPoint.

- -The second line of output shows that the field access rp.x refers to the field x declared in class RealPoint. This field is of type float, and this second line of output accordingly displays floating-point values. Incidentally, this also illustrates the fact that the method name show is overloaded; the types of the arguments in the method invocation dictate which of the two definitions will be invoked.

- -The last two lines of output show that the method invocations p.getX() and rp.getX() each invoke the getX method declared in class RealPoint. Indeed, there is no way to invoke the getX method of class Point for an instance of class RealPoint from outside the body of RealPoint, no matter what the type of the variable we may use to hold the reference to the object. Thus, we see that fields and methods behave differently: hiding is different from overriding.

- -

8.4.8.5 Example: Invocation of Hidden Class Methods

- -A hidden class (static) method can be invoked by using a reference whose type -is the class that actually contains the declaration of the method. In this respect, -hiding of static methods is different from overriding of instance methods. The -example: -

-

- -

- -

-


-class Super {
-	static String greeting() { return "Goodnight"; }
-	String name() { return "Richard"; }
-}
-
-class Sub extends Super { - static String greeting() { return "Hello"; } - String name() { return "Dick"; } -} -
-class Test { - public static void main(String[] args) { - Super s = new Sub(); - System.out.println(s.greeting() + ", " + s.name()); - } -} -
-produces the output: -

Goodnight, Dick
-
-because the invocation of greeting uses the type of s, namely Super, to figure -out, at compile time, which class method to invoke, whereas the invocation of -name uses the class of s, namely Sub, to figure out, at run time, which instance -method to invoke. -

-

8.4.8.6 Large Example of Overriding

- -Overriding makes it easy for subclasses to extend the behavior of an existing -class, as shown in this example: -


import java.io.OutputStream; -

import java.io.IOException; -

-class BufferOutput {
-
private OutputStream o; -

BufferOutput(OutputStream o) { this.o = o; } -

protected byte[] buf = new byte[512]; -

protected int pos = 0; -
- public void putchar(char c) throws IOException { - if (pos == buf.length) - flush(); - buf[pos++] = (byte)c; - } -

-	public void putstr(String s) throws IOException {
-		for (int i = 0; i < s.length(); i++)
-			putchar(s.charAt(i));
-	}
-
- public void flush() throws IOException { - o.write(buf, 0, pos); - pos = 0; - } -
} -
-class LineBufferOutput extends BufferOutput { -
LineBufferOutput(OutputStream o) { super(o); } -
- public void putchar(char c) throws IOException { - super.putchar(c); - if (c == '\n') - flush(); - } -
} -
-class Test { - public static void main(String[] args)
- throws IOException
- { - LineBufferOutput lbo =
- new LineBufferOutput(System.out); - lbo.putstr("lbo\nlbo"); - System.out.print("print\n"); - lbo.putstr("\n"); - } -} -
-This example produces the output: -


-lbo
-print
-lbo
-
-The class BufferOutput implements a very simple buffered version of an OutputStream, flushing the output when the buffer is full or flush is invoked. The subclass LineBufferOutput declares only a constructor and a single method putchar, which overrides the method putchar of BufferOutput. It inherits the methods putstr and flush from class Buffer.

- -In the putchar method of a LineBufferOutput object, if the character argument is a newline, then it invokes the flush method. The critical point about overriding in this example is that the method putstr, which is declared in class BufferOutput, invokes the putchar method defined by the current object this, which is not necessarily the putchar method declared in class BufferOutput.

- -Thus, when putstr is invoked in main using the LineBufferOutput object lbo, the invocation of putchar in the body of the putstr method is an invocation of the putchar of the object lbo, the overriding declaration of putchar that checks for a newline. This allows a subclass of BufferOutput to change the behavior of the putstr method without redefining it.

- -Documentation for a class such as BufferOutput, which is designed to be extended, should clearly indicate what is the contract between the class and its subclasses, and should clearly indicate that subclasses may override the putchar method in this way. The implementor of the BufferOutput class would not, therefore, want to change the implementation of putstr in a future implementation of BufferOutput not to use the method putchar, because this would break the preexisting contract with subclasses. See the further discussion of binary compatibility in §13, especially §13.2.

- -

8.4.8.7 Example: Incorrect Overriding because of Throws

- -This example uses the usual and conventional form for declaring a new exception -type, in its declaration of the class BadPointException: -


-class BadPointException extends Exception {
-	BadPointException() { super(); }
-	BadPointException(String s) { super(s); }
-}
-
-class Point {
-	int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-class CheckedPoint extends Point { - void move(int dx, int dy) throws BadPointException { - if ((x + dx) < 0 || (y + dy) < 0) - throw new BadPointException(); - x += dx; y += dy; - } -} -
-This example results in a compile-time error, because the override of method -move in class CheckedPoint declares that it will throw a checked exception that -the move in class Point has not declared. If this were not considered an error, an -invoker of the method move on a reference of type Point could find the contract -between it and Point broken if this exception were thrown. -

-Removing the throws clause does not help:

-


-class CheckedPoint extends Point {
-	void move(int dx, int dy) {
-		if ((x + dx) < 0 || (y + dy) < 0)
-			throw new BadPointException();
-		x += dx; y += dy;
-	}
-}
-
-A different compile-time error now occurs, because the body of the method move -cannot throw a checked exception, namely BadPointException, that does not -appear in the throws clause for move. -

-

8.5 Static Initializers

- -Any static initializers declared in a class are executed when the class is initialized -and, together with any field initializers (§8.3.2) for class variables, may be used to -initialize the class variables of the class (§12.4). -

-It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.5) with a checked exception (§11.2).

- -The static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. This restriction is designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:

-


-class Z {
-	static int i = j + 2; 
-	static int j = 4;
-}
-
-and: -


-class Z {
-	static { i = j + 2; }
-	static int i, j;
-	static { j = 4; }
-}
-
-result in compile-time errors. -

-Accesses to class variables by methods are not checked in this way, so: -


-class Z {
-	static int peek() { return j; }
- static int i = peek(); - static int j = 1; -} -
-class Test { - public static void main(String[] args) { - System.out.println(Z.i); - }
-} -
-produces the output: -

0
-
-because the variable initializer for i uses the class method peek to access the -value of the variable j before j has been initialized by its variable initializer, at -which point it still has its default value (§4.5.4). -

-If a return statement (§14.15) appears anywhere within a static initializer, then a compile-time error occurs.

- -If the keyword this (§15.7.2) or the keyword super (§15.10, §15.11) appears anywhere within a static initializer, then a compile-time error occurs.

- -

8.6 Constructor Declarations

- -A constructor is used in the creation of an object that is an instance of a class: -

-The SimpleTypeName in the ConstructorDeclarator must be the simple name of -the class that contains the constructor declaration; otherwise a compile-time error -occurs. In all other respects, the constructor declaration looks just like a method -declaration that has no result type. -

-Here is a simple example:

-


-class Point {
-	int x, y;
-	Point(int x, int y) { this.x = x; this.y = y; }
-}
-
-Constructors are invoked by class instance creation expressions (§15.8), by the newInstance method of class Class (§20.3), by the conversions and concatenations caused by the string concatenation operator + (§15.17.1), and by explicit constructor invocations from other constructors (§8.6.5). Constructors are never invoked by method invocation expressions (§15.11).

- -Access to constructors is governed by access modifiers (§6.6). This is useful, for example, in preventing instantiation by declaring an inaccessible constructor (§8.6.8).

- -Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

- -

8.6.1 Formal Parameters

- -The formal parameters of a constructor are identical in structure and behavior to -the formal parameters of a method (§8.4.1). -

-

8.6.2 Constructor Signature

- -The signature of a constructor is identical in structure and behavior to the signature -of a method (§8.4.2). -

-

8.6.3 Constructor Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. -A compile-time error occurs if the same modifier appears more than once in a -constructor declaration, or if a constructor declaration has more than one of the -access modifiers public, protected, and private. -

-Unlike methods, a constructor cannot be abstract, static, final, native, or synchronized. A constructor is not inherited, so there is no need to declare it final and an abstract constructor could never be implemented. A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static. There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work. The lack of native constructors is an arbitrary language design choice that makes it easy for an implementation of the Java Virtual Machine to verify that superclass constructors are always properly invoked during object creation.

- -

8.6.4 Constructor Throws

- -The throws clause for a constructor is identical in structure and behavior to the -throws clause for a method (§8.4.4). -

-

8.6.5 Constructor Body

- -The first statement of a constructor body may be an explicit invocation of another -constructor of the same class, written as this followed by a parenthesized argument -list, or an explicit invocation of a constructor of the direct superclass, written -as super followed by a parenthesized argument list. -

-It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.

- -If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

- -Except for the possibility of explicit constructor invocations, the body of a constructor is like the body of a method (§8.4.5). A return statement (§14.15) may be used in the body of a constructor if it does not include an expression.

- -In the example:

-


-class Point {
-
int x, y; -

Point(int x, int y) { this.x = x; this.y = y; } -
} -
-class ColoredPoint extends Point { -
static final int WHITE = 0, BLACK = 1; -

int color; -
- ColoredPoint(int x, int y) { - this(x, y, WHITE); - } -
- ColoredPoint(int x, int y, int color) { - super(x, y);
- this.color = color;
- } -
} -
-the first constructor of ColoredPoint invokes the second, providing an additional -argument; the second constructor of ColoredPoint invokes the constructor of its -superclass Point, passing along the coordinates. -

-An explicit constructor invocation statement may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs. For example, if the first constructor of ColoredPoint in the example above were changed to:

-


-	ColoredPoint(int x, int y) {
-		this(x, y, color);
-	}
-
-then a compile-time error would occur, because an instance variable cannot be -used within a superclass constructor invocation. -

-An invocation of the constructor of the direct superclass, whether it actually appears as an explicit constructor invocation statement or is provided automatically (§8.6.7), performs an additional implicit action after a normal return of control from the constructor: all instance variables that have initializers are initialized at that time, in the textual order in which they appear in the class declaration. An invocation of another constructor in the same class using the keyword this does not perform this additional implicit action.

- -§12.5 describes the creation and initialization of new class instances.

- -

8.6.6 Constructor Overloading

- -Overloading of constructors is identical in behavior to overloading of methods. -The overloading is resolved at compile time by each class instance creation -expression (§15.8). -

-

8.6.7 Default Constructor

- -If a class contains no constructor declarations, then a default constructor that -takes no parameters is automatically provided: -

-A compile-time error occurs if a default constructor is provided by the compiler but the superclass does not have a constructor that takes no arguments.

- -If the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); otherwise, the default constructor has the default access implied by no access modifier. Thus, the example:

-


-public class Point {
-	int x, y;
-}
-
-is equivalent to the declaration: -


-public class Point {
-	int x, y;
-	public Point() { super(); }
-}
-
-where the default constructor is public because the class Point is public. -

-

8.6.8 Preventing Instantiation of a Class

- -A class can be designed to prevent code outside the class declaration from creating -instances of the class by declaring at least one constructor, to prevent the creation -of an implicit constructor, and declaring all constructors to be private. A -public class can likewise prevent the creation of instances outside its package by -declaring at least one constructor, to prevent creation of a default constructor with -public access, and declaring no constructor that is public. -

-Thus, in the example:

-


-class ClassOnly {
-	private ClassOnly() { }
-	static String just = "only the lonely";
-}
-
-the class ClassOnly cannot be instantiated, while in the example: -


package just; -

-public class PackageOnly {
-	PackageOnly() { }
-	String[] justDesserts = { "cheesecake", "ice cream" };
-}
-
-the class PackageOnly can be instantiated only within the package just, in -which it is declared. -

-

- - -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - -The Java Language Specification - Interfaces - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 9

- -

Interfaces

-

- -An interface declaration introduces a new reference type whose members are -constants and abstract methods. This type has no implementation, but otherwise -unrelated classes can implement it by providing implementations for its abstract -methods. -

-Java programs can use interfaces to make it unnecessary for related classes to share a common abstract superclass or to add methods to Object.

- -An interface may be declared to be an direct extension of one or more other interfaces, meaning that it implicitly specifies all the abstract methods and constants of the interfaces it extends, except for any constants that it may hide.

- -A class may be declared to directly implement one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do. This (multiple) interface inheritance allows objects to support (multiple) common behaviors without sharing any implementation.

- -A variable whose declared type is an interface type may have as its value a reference to any object that is an instance of a class declared to implement the specified interface. It is not sufficient that the class happen to implement all the abstract methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface.

- -

9.1 Interface Declarations

- -An interface declaration specifies a new reference type: -

-A compile-time error occurs if the Identifier naming an interface appears as the -name of any other class or interface in the same package. A compile-time error -also occurs if the Identifier naming an interface appears as the name by which a -class or interface is to be known via a single-type-import declaration (§7.5.1) in -the compilation unit containing the interface declaration. In the example: -


class Point { int x, y; } -
interface Point { void move(int dx, int dy); } -
-a compile-time error occurs because a class and an interface in the same package -cannot have the same name. -

-

9.1.1 Scope of an Interface Type Name

- -The Identifier specifies the name of the interface and has as its scope the entire -package in which it is declared. This is the same scoping rule as for class type -names; see §8.1.1 for an example involving classes. -

-

9.1.2 Interface Modifiers

- -An interface declaration may be preceded by interface modifiers: -

-The access modifier public is discussed in §6.6. A compile-time error occurs if -the same modifier appears more than once in an interface declaration. -

-

9.1.2.1 abstract Interfaces

- -Every interface is implicitly abstract. This modifier is obsolete and should not -be used in new Java programs. -

-

9.1.3 Superinterfaces

- -If an extends clause is provided, then the interface being declared extends each -of the other named interfaces and therefore inherits the methods and constants of -each of the other named interfaces. These other named interfaces are the direct -superinterfaces of the interface being declared. Any class that implements the -declared interface is also considered to implement all the interfaces that this interface -extends and that are accessible to the class. -

-The following is repeated from §4.3 to make the presentation here clearer: -

-Each InterfaceType in the extends clause of an interface declaration must name an accessible interface type; otherwise a compile-time error occurs.

- -A compile-time error occurs if there is a circularity such that an interface directly or indirectly extends itself.

- -There is no analogue of the class Object for interfaces; that is, while every class is an extension of class Object, there is no single interface of which all interfaces are extensions.

- -The superinterface relationship is the transitive closure of the direct superinterface relationship. An interface K is a superinterface of interface I if either of the following is true:

-

-Interface I is said to be a subinterface of interface K whenever K is a superinterface -of I. -

-

9.1.4 Interface Body and Member Declarations

- -The body of an interface may declare members of the interface: -

-The scope of the name of a member declared in an interface type is the entire body -of the interface type declaration. -

-

9.1.5 Access to Interface Member Names

- -All interface members are implicitly public. They are accessible outside the -package where the interface is declared if the interface is also declared public -and the package containing the interface is accessible as described in §7.1. -

-

9.2 Interface Members

- -The members of an interface are those members inherited from direct superinterfaces -and those members declared in the interface. -

-The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields that it hides and methods that it overrides.

- -

9.3 Field (Constant) Declarations

- -Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted, but strongly discouraged as a matter of style, to redundantly specify any or all of these modifiers for such fields.

- -A constant declaration in an interface must not include any of the modifiers synchronized, transient, or volatile, or a compile-time error occurs.

- -It is possible for an interface to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the interface to refer to either field by its simple name will result in a compile-time error, because such a reference is ambiguous.

- -There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.

- -

9.3.1 Initialization of Fields in Interfaces

- -Every field in the body of an interface must have an initialization expression, -which need not be a constant expression. The variable initializer is evaluated and -the assignment performed exactly once, when the interface is initialized (§12.4). -

-A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface. Thus:

-


-interface Test {
-	float f = j;
-	int j = 1;
-	int k = k+1;
-}
-
-causes two compile-time errors, because j is referred to in the initialization of f -before j is declared and because the initialization of k refers to k itself. -

-(One subtlety here is that, at run time, fields that are initialized with compile-time constant values are initialized first. This applies also to static final fields in classes (§8.3.2.1). This means, in particular, that these fields will never be observed to have their default initial values (§4.5.4), even by devious programs. See §12.4.2 and §13.4.8 for more discussion.)

- -If the keyword this (§15.7.2) or the keyword super (15.10.2, 15.11) occurs in an initialization expression for a field of an interface, then a compile-time error occurs.

- -

9.3.2 Examples of Field Declarations

- -The following example illustrates some (possibly subtle) points about field declarations. - -

-

9.3.2.1 Ambiguous Inherited Fields

- -If two fields with the same name are inherited by an interface because, for example, -two of its direct superinterfaces declare fields with that name, then a single -ambiguous member results. Any use of this ambiguous member will result in a -compile-time error. Thus in the example: -


-interface BaseColors {
-	int RED = 1, GREEN = 2, BLUE = 4;
-}
-
-interface RainbowColors extends BaseColors { - int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7; -} -
-interface PrintColors extends BaseColors { - int YELLOW = 8, CYAN = 16, MAGENTA = 32; -} -
-interface LotsOfColors extends RainbowColors, PrintColors { - int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90; -} -
-the interface LotsOfColors inherits two fields named YELLOW. This is all right as -long as the interface does not contain any reference by simple name to the field -YELLOW. (Such a reference could occur within a variable initializer for a field.) -

-Even if interface PrintColors were to give the value 3 to YELLOW rather than the value 8, a reference to field YELLOW within interface LotsOfColors would still be considered ambiguous.

- -

9.3.2.2 Multiply Inherited Fields

- -If a single field is inherited multiple times from the same interface because, for -example, both this interface and one of this interface's direct superinterfaces -extend the interface that declares the field, then only a single member results. This -situation does not in itself cause a compile-time error. -

-In the example in the previous section, the fields RED, GREEN, and BLUE are inherited by interface LotsOfColors in more than one way, through interface RainbowColors and also through interface PrintColors, but the reference to field RED in interface LotsOfColors is not considered ambiguous because only one actual declaration of the field RED is involved.

- -

9.4 Abstract Method Declarations

- -The access modifier public is discussed in §6.6. A compile-time error occurs if -the same modifier appears more than once in an abstract method declaration. -

-Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block. For compatibility with older versions of Java, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

- -Every method declaration in the body of an interface is implicitly public. It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

- -Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because in Java static methods cannot be abstract.

- -Note that a method declared in an interface must not be declared native or synchronized, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties. However, a method declared in an interface may be implemented by a method that is declared native or synchronized in a class that implements the interface.

- -Note that a method declared in an interface must not be declared final or a compile-time error occurs. However, a method declared in an interface may be implemented by a method that is declared final in a class that implements the interface.

- -

9.4.1 Inheritance and Overriding

- -If the interface declares a method, then the declaration of that method is said to -override any and all methods with the same signature in the superinterfaces of the -interface that would otherwise be accessible to code in this interface. -

-If a method declaration in an interface overrides the declaration of a method in another interface, a compile-time error occurs if the methods have different return types or if one has a return type and the other is void. Moreover, a method declaration must not have a throws clause that conflicts (§8.4.4) with that of any method that it overrides; otherwise, a compile-time error occurs.

- -Methods are overridden on a signature-by-signature basis. If, for example, an interface declares two public methods with the same name, and a subinterface overrides one of them, the subinterface still inherits the other method.

- -An interface inherits from its direct superinterfaces all methods of the superinterfaces that are not overridden by a declaration in the interface.

- -It is possible for an interface to inherit more than one method with the same signature (§8.4.2). Such a situation does not in itself cause a compile-time error. The interface is considered to inherit all the methods. However, a compile-time error occurs if, for any two such inherited methods, either they have different return types or one has a return type and the other is void. (The throws clauses do not cause errors in this case.)

- -There might be several paths by which the same method declaration is inherited from an interface. This fact causes no difficulty and never of itself results in a compile-time error.

- -

9.4.2 Overloading

- -If two methods of an interface (whether both declared in the same interface, or -both inherited by a interface, or one declared and one inherited) have the same -name but different signatures, then the method name is said to be overloaded. This -fact causes no difficulty and never of itself results in a compile-time error. There is -no required relationship between the return types or between the throws clauses -of two methods with the same name but different signatures. -

-

9.4.3 Examples of Abstract Method Declarations

- -The following examples illustrate some (possibly subtle) points about abstract -method declarations. -

-

9.4.3.1 Example: Overriding

- -Methods declared in interfaces are abstract and thus contain no implementation. -About all that can be accomplished by an overriding method declaration, other -than to affirm a method signature, is to restrict the exceptions that might be thrown -by an implementation of the method. Here is a variation of the example shown in -§8.4.3.1: -


-class BufferEmpty extends Exception {
-	BufferEmpty() { super(); }
-	BufferEmpty(String s) { super(s); }
-}
-
-class BufferError extends Exception { - BufferError() { super(); } - BufferError(String s) { super(s); } -} -
-public interface Buffer { - char get() throws BufferEmpty, BufferError; -} -
-public interface InfiniteBuffer extends Buffer { - char get() throws BufferError; // override -} -
-

9.4.3.2 Example: Overloading

- -In the example code: -


-interface PointInterface {
-	void move(int dx, int dy);
-}
-
-interface RealPointInterface extends PointInterface { - void move(float dx, float dy); - void move(double dx, double dy); -} -
-the method name move is overloaded in interface RealPointInterface with -three different signatures, two of them declared and one inherited. Any class that -implements interface RealPointInterface must provide implementations of all -three method signatures. -

-

- - -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - -The Java Language Specification - Arrays - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 10

- -

Arrays

-

- -Java arrays are objects (§4.3.1), are dynamically created, and may be assigned -to variables of type Object (§4.3.2). All methods of class Object may be invoked -on an array. -

-An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to , inclusive.

- -All the components of an array have the same type, called the component type of the array. If the component type of an array is T, then the type of the array itself is written T[].

- -The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the element type of the original array, and the components at this level of the data structure are called the elements of the original array.

- -There is one situation in which an element of an array can be an array: if the element type is Object, then some or all of the elements may be arrays, because any array object can be assigned to any variable of type Object.

- -

10.1 Array Types

- -An array type is written as the name of an element type followed by some number -of empty pairs of square brackets []. The number of bracket pairs indicates the -depth of array nesting. An array's length is not part of its type. -

-The element type of an array may be any type, whether primitive or reference. In particular:

-

-Array types are used in declarations and in cast expressions (§15.15).

- -

10.2 Array Variables

- -A variable of array type holds a reference to an object. Declaring a variable of -array type does not create an array object or allocate any space for array components. -It creates only the variable itself, which can contain a reference to an array. -However, the initializer part of a declarator (§8.3) may create an array, a reference -to which then becomes the initial value of the variable. -

-Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.

- -Here are examples of declarations of array variables that do not create arrays:

-


-int[] ai;							// array of int
-short[][] as;							// array of array of short
-Object[]			ao,				// array of Object
-			otherAo;				// array of Object
-short		s,					// scalar short 
-		aas[][];					// array of array of short
-
-Here are some examples of declarations of array variables that create array -objects: -


-Exception ae[] = new Exception[3]; 
-Object aao[][] = new Exception[2][3];
-int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
-char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
-				 'S', 't', 'r', 'i', 'n', 'g' }; 
-String[] aas = { "array", "of", "String", };
-
-The [] may appear as part of the type at the beginning of the declaration, or as -part of the declarator for a particular variable, or both, as in this example: -

byte[] rowvector, colvector, matrix[];
-
-This declaration is equivalent to: -

byte rowvector[], colvector[], matrix[][];
-
-Once an array object is created, its length never changes. To make an array variable -refer to an array of different length, a reference to a different array must be -assigned to the variable. -

-If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A. This may result in a run-time exception on a later assignment; see §10.10 for a discussion.

- -

10.3 Array Creation

- -An array is created by an array creation expression (§15.9) or an array initializer -(§10.6). -

-An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable length.

- -An array initializer creates an array and provides initial values for all its components. (Contrast this with C and C++, where it is possible for an array initializer to specify initial values for some but not all of the components of an array.)

- -

10.4 Array Access

- -A component of an array is accessed by an array access expression (§15.12) that -consists of an expression whose value is an array reference followed by an indexing -expression enclosed by [ and ], as in A[i]. All arrays are 0-origin. An array -with length n can be indexed by the integers 0 to n-1. -

-Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values. An attempt to access an array component with a long index value results in a compile-time error.

- -All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an IndexOutOfBoundsException to be thrown.

- -

10.5 Arrays: A Simple Example

- -The example: -


-class Gauss {
-	public static void main(String[] args) {
-		int[] ia = new int[101];
-		for (int i = 0; i < ia.length; i++)
-			ia[i] = i;
-		int sum = 0;
-		for (int i = 0; i < ia.length; i++)
-			sum += ia[i];
-		System.out.println(sum);
-	}
-}
-
-that produces output: -

5050
-
-declares a variable ia that has type array of int, that is, int[]. The variable ia is -initialized to reference a newly created array object, created by an array creation -expression (§15.9). The array creation expression specifies that the array should -have 101 components. The length of the array is available using the field length, -as shown. -

-The example program fills the array with the integers from 0 to 100, sums these integers, and prints the result.

- -

10.6 Arrays Initializers

- -An array initializer may be specified in a declaration, creating an array and providing -some initial values: -

-The following is repeated from §8.3 to make the presentation here clearer: -

-An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".

- -The length of the constructed array will equal the number of expressions.

- -Each expression specifies a value for one array component. Each expression must be assignment-compatible (§5.2) with the array's component type, or a compile-time error results.

- -If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.

- -A trailing comma may appear after the last expression in an array initializer and is ignored.

- -As an example:

-


-class Test {
-	public static void main(String[] args) {
-		int ia[][] = { {1, 2}, null };
-		for (int i = 0; i < 2; i++)
-			for (int j = 0; j < 2; j++)
-				System.out.println(ia[i][j]);
-	}
-}
-
-prints: -


-1
-2
-
-before causing a NullPointerException in trying to index the second component -of the array ia, which is a null reference. -

-

10.7 Array Members

- -The members of an array type are all of the following: -

-An array thus has the same methods as the following class: -


-class A implements Cloneable {
-	public final int length = X;
-	public Object clone() {
-		try {
-			return super.clone();
-		} catch (CloneNotSupportedException e) {
-			throw new InternalError(e.getMessage());
-		}
-	}
-
} -
-Every array implements interface Cloneable. That arrays are cloneable is shown -by the test program: -


-class Test {
-	public static void main(String[] args) {
-		int ia1[] = { 1, 2 };
-		int ia2[] = (int[])ia1.clone();
-		System.out.print((ia1 == ia2) + " ");
-		ia1[1]++;
-		System.out.println(ia2[1]);
-	}
-}
-
-which prints: -

false 2
-
-showing that the components of the arrays referenced by ia1 and ia2 are different -variables. (In some early implementations of Java this example failed to compile -because the compiler incorrectly believed that the clone method for an array could -throw a CloneNotSupportedException.) -

-A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared, as shown by the example program:

-


-class Test {
-	public static void main(String[] args) throws Throwable {
-		int ia[][] = { { 1 , 2}, null };
-		int ja[][] = (int[][])ia.clone();
-		System.out.print((ia == ja) + " ");
-		System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
-	}
-}
-
-which prints: -

false true
-
-showing that the int[] array that is ia[0] and the int[] array that is ja[0] are -the same array. -

-

10.8 Class Objects for Arrays

- -Every array has an associated Class object, shared with all other arrays with the -same component type. The superclass of an array type is considered to be Object, -as shown by the following example code: -


-class Test {
-	public static void main(String[] args) {
-		int[] ia = new int[3];
-		System.out.println(ia.getClass());
-		System.out.println(ia.getClass().getSuperclass());
-	}
-}
-
-which prints: -


-class [I
-class java.lang.Object
-
-where the string "[I" is the run-time type signature for the class object "array -with component type int" (§20.1.1). -

-

10.9 An Array of Characters is Not a String

- -In Java, unlike C, an array of char is not a String (§20.12), and neither a String -nor an array of char is terminated by '\u0000' (the NUL character). -

-A Java String object is immutable, that is, its contents never change, while an array of char has mutable elements. The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters (§20.13).

- -

10.10 Array Store Exception

- -If an array variable v has type A[], where A is a reference type, then v can hold a -reference to an instance of any array type B[], provided B can be assigned to A. -

-Thus, the example:

-


-class Point { int x, y; }
-
class ColoredPoint extends Point { int color; } -

-class Test {
-	public static void main(String[] args) {
-		ColoredPoint[] cpa = new ColoredPoint[10];
-		Point[] pa = cpa;
-		System.out.println(pa[1] == null);
-		try {
-			pa[0] = new Point();
-		} catch (ArrayStoreException e) {
-			System.out.println(e);
-		}
-	}
-}
-
-produces the output: -


-true
-java.lang.ArrayStoreException
-
-Here the variable pa has type Point[] and the variable cpa has as its value a reference -to an object of type ColoredPoint[]. A ColoredPoint can be assigned -to a Point; therefore, the value of cpa can be assigned to pa. -

-A reference to this array pa, for example, testing whether pa[1] is null, will not result in a run-time type error. This is because the element of the array of type ColoredPoint[] is a ColoredPoint, and every ColoredPoint can stand in for a Point, since Point is the superclass of ColoredPoint.

- -On the other hand, an assignment to the array pa can result in a run-time error. At compile time, an assignment to an element of pa is checked to make sure that the value assigned is a Point. But since pa holds a reference to an array of ColoredPoint, the assignment is valid only if the type of the value assigned at run-time is, more specifically, a ColoredPoint.

- -Java checks for such a situation at run-time to ensure that the assignment is valid; if not, an ArrayStoreException is thrown. More formally: an assignment to an element of an array whose type is A[], where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A.

- - -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - -The Java Language Specification - Blocks and Statements - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 14

- -

Blocks and Statements

-

- -The sequence of execution of a Java program is controlled by statements, -which are executed for their effect and do not have values. -

-Some statements contain other statements as part of their structure; such other statements are substatements of the statement. We say that statement S immediately contains statement U if there is no statement T different from S and U such that S contains T and T contains U. In the same manner, some statements contain expressions (§15) as part of their structure.

- -The first section of this chapter discusses the distinction between normal and abrupt completion of statements (§14.1). Most of the remaining sections explain the various kinds of statements, describing in detail both their normal behavior and any special treatment of abrupt completion.

- -Blocks are explained first (§14.2), because they can appear in certain places where other kinds of statements are not allowed, and because one other kind of statement, a local variable declaration statement (§14.3), must be immediately contained within a block.

- -Next a grammatical maneuver is explained that sidesteps the familiar "dangling else" problem (§14.4).

- -Statements that will be familiar to C and C++ programmers are the empty (§14.5), labeled (§14.6), expression (§14.7), if (§14.8), switch (§14.9), while (§14.10), do (§14.11), for (§14.12), break (§14.13), continue (§14.14), and return (§14.15) statements.

- -Unlike C and C++, Java has no goto statement. However, the break and continue statements are extended in Java to allow them to mention statement labels.

- -The Java statements that are not in the C language are the throw (§14.16), synchronized (§14.17), and try (§14.18) statements.

- -The last section (§14.19) of this chapter addresses the requirement that every statement be reachable in a certain technical sense.

- -

14.1 Normal and Abrupt Completion of Statements

- -Every statement has a normal mode of execution in which certain computational -steps are carried out. The following sections describe the normal mode of execution -for each kind of statement. If all the steps are carried out as described, with no -indication of abrupt completion, the statement is said to complete normally. However, -certain events may prevent a statement from completing normally: -

-If such an event occurs, then execution of one or more statements may be terminated before all steps of their normal mode of execution have completed; such statements are said to complete abruptly. An abrupt completion always has an associated reason, which is one of the following:

-

-The terms "complete normally" and "complete abruptly" also apply to the evaluation of expressions (§15.5). The only reason an expression can complete abruptly is that an exception is thrown, because of either a throw with a given value (§14.16) or a run-time exception or error (§11, §15.5).

- -If a statement evaluates an expression, abrupt completion of the expression always causes the immediate abrupt completion of the statement, with the same reason. All succeeding steps in the normal mode of execution are not performed.

- -Unless otherwise specified in this chapter, abrupt completion of a substatement causes the immediate abrupt completion of the statement itself, with the same reason, and all succeeding steps in the normal mode of execution of the statement are not performed.

- -Unless otherwise specified, a statement completes normally if all expressions it evaluates and all substatements it executes complete normally.

- -

14.2 Blocks

- -A block is a sequence of statements and local variable declaration statements -within braces. -

-A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.

- -

14.3 Local Variable Declaration Statements

- -A local variable declaration statement declares one or more local variable names. -

-The following are repeated from §8.3 to make the presentation here clearer: -

-Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.

- -A local variable declaration can also appear in the header of a for statement (§14.12). In this case it is executed in the same manner as if it were part of a local variable declaration statement.

- -

14.3.1 Local Variable Declarators and Types

- -Each declarator in a local variable declaration declares one local variable, whose -name is the Identifier that appears in the declarator. -

-The type of the variable is denoted by the Type that appears at the start of the local variable declaration, followed by any bracket pairs that follow the Identifier in the declarator. Thus, the local variable declaration:

-

int a, b[], c[][];
-
-is equivalent to the series of declarations: -


-int a;
-int[] b;
-int[][] c;
-
-Brackets are allowed in declarators as a nod to the tradition of C and C++. The -general rule, however, also means that the local variable declaration: -

float[][] f[][], g[][][], h[];													// Yechh!
-
-is equivalent to the series of declarations: -


-float[][][][] f;
-float[][][][][] g;
-float[][][] h;
-
-We do not recommend such "mixed notation" for array declarations. -

-

14.3.2 Scope of Local Variable Declarations

- -The scope of a local variable declared in a block is the rest of the block, including -its own initializer. The name of the local variable parameter may not be redeclared -as a local variable or exception parameter within its scope, or a compile-time error -occurs; that is, hiding the name of a local variable is not permitted. -

-A local variable cannot be referred to using a qualified name (§6.6), only a simple name.

- -The example:

-


-class Test {
-	static int x;
-	public static void main(String[] args) {
-		int x = x;
-	}
-}
-
-causes a compile-time error because the initialization of x is within the scope of -the declaration of x as a local variable, and the local x does not yet have a value -and cannot be used. -

-The following program does compile:

-


-class Test {
-	static int x;
-	public static void main(String[] args) {
-		int x = (x=2)*2;
-		System.out.println(x);
-	}
-}
-
-because the local variable x is definitely assigned (§16) before it is used. It prints: -

4
-
-Here is another example:

-


-class Test {
-	public static void main(String[] args) {
-		System.out.print("2+1=");
-		int two = 2, three = two + 1;
-		System.out.println(three);
-	}
-}
-
-which compiles correctly and produces the output: -

2+1=3
-
-The initializer for three can correctly refer to the variable two declared in an earlier -declarator, and the method invocation in the next line can correctly refer to the -variable three declared earlier in the block. -

-The scope of a local variable declared in a for statement is the rest of the for statement, including its own initializer.

- -If a declaration of an identifier as a local variable appears within the scope of a parameter or local variable of the same name, a compile-time error occurs. Thus the following example does not compile:

-


-class Test {
-	public static void main(String[] args) {
-		int i;
-		for (int i = 0; i < 10; i++)
-			System.out.println(i);
-	}
-}
-
-This restriction helps to detect some otherwise very obscure bugs. (A similar -restriction on hiding of members by local variables was judged impractical, -because the addition of a member in a superclass could cause subclasses to have to -rename local variables.) -

-On the other hand, local variables with the same name may be declared in two separate blocks or for statements neither of which contains the other. Thus:

-


-class Test {
-	public static void main(String[] args) {
-		for (int i = 0; i < 10; i++)
-			System.out.print(i + " ");
-		for (int i = 10; i > 0; i--)
-			System.out.print(i + " ");
-		System.out.println();
-	}
-}
-
-compiles without error and, when executed, produces the output: -

0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
-
-

14.3.3 Hiding of Names by Local Variables

- -If a name declared as a local variable is already declared as a field or type name, -then that outer declaration is hidden throughout the scope of the local variable. -The field or type name can almost always (§6.8) still be accessed using an appropriately -qualified name. For example, the keyword this can be used to access a -hidden field x, using the form this.x. Indeed, this idiom typically appears in constructors -(§8.6): -


-class Pair {
-	Object first, second;
-	public Pair(Object first, Object second) {
-		this.first = first;
-		this.second = second;
-	}
-}
-
-In this example, the constructor takes parameters having the same names as the -fields to be initialized. This is simpler than having to invent different names for -the parameters and is not too confusing in this stylized context. In general, however, -it is considered poor style to have local variables with the same names as -fields. -

-

14.3.4 Execution of Local Variable Declarations

- -A local variable declaration statement is an executable statement. Every time it is -executed, the declarators are processed in order from left to right. If a declarator -has an initialization expression, the expression is evaluated and its value is -assigned to the variable. If a declarator does not have an initialization expression, -then a Java compiler must prove, using exactly the algorithm given in §16, that -every reference to the variable is necessarily preceded by execution of an assignment -to the variable. If this is not the case, then a compile-time error occurs. -

-Each initialization (except the first) is executed only if the evaluation of the preceding initialization expression completes normally. Execution of the local variable declaration completes normally only if evaluation of the last initialization expression completes normally; if the local variable declaration contains no initialization expressions, then executing it always completes normally.

- -

14.4 Statements

- -There are many kinds of statements in the Java language. Most correspond to -statements in the C and C++ languages, but some are unique to Java. -

-As in C and C++, the Java if statement suffers from the so-called "dangling else problem," illustrated by this misleadingly formatted example:

-


-if (door.isOpen())
-	if (resident.isVisible())
-		resident.greet("Hello!");
-else door.bell.ring();								// A "dangling else"
-
-The problem is that both the outer if statement and the inner if statement might -conceivably own the else clause. In this example, one might surmise that the programmer -intended the else clause to belong to the outer if statement. The Java -language, like C and C++ and many languages before them, arbitrarily decree that -an else clause belongs to the innermost if to which it might possibly belong. -This rule is captured by the following grammar: -

-The following are repeated from §14.8 to make the presentation here clearer: -

-Statements are thus grammatically divided into two categories: those that might end in an if statement that has no else clause (a "short if statement") and those that definitely do not. Only statements that definitely do not end in a short if statement may appear as an immediate substatement before the keyword else in an if statement that does have an else clause. This simple rule prevents the "dangling else" problem. The execution behavior of a statement with the "no short if" restriction is identical to the execution behavior of the same kind of statement without the "no short if" restriction; the distinction is drawn purely to resolve the syntactic difficulty.

- -

14.5 The Empty Statement

- -An empty statement does nothing. -

-Execution of an empty statement always completes normally. -

-

14.6 Labeled Statements

- -Statements may have label prefixes. -

-The Identifier is declared to be the label of the immediately contained Statement. -

-Unlike C and C++, the Java language has no goto statement; identifier statement labels are used with break (§14.13) or continue (§14.14) statements appearing anywhere within the labeled statement.

- -A statement labeled by an identifier must not appear anywhere within another statement labeled by the same identifier, or a compile-time error will occur. Two statements can be labeled by the same identifier only if neither statement contains the other.

- -There is no restriction against using the same identifier as a label and as the name of a package, class, interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not hide a package, class, interface, method, field, parameter, or local variable with the same name. Use of an identifier as a local variable or as the parameter of an exception handler (§14.18) does not hide a statement label with the same name.

- -A labeled statement is executed by executing the immediately contained Statement. If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason.

- -

14.7 Expression Statements

- -Certain kinds of expressions may be used as statements by following them with -semicolons: -

-An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.

- -Unlike C and C++, the Java language allows only certain forms of expressions to be used as expression statements. Note that Java does not allow a "cast to void"-void is not a type in Java-so the traditional C trick of writing an expression statement such as:

-

(void) ... ;								// This idiom belongs to C, not to Java!
-
-does not work in Java. On the other hand, Java allows all the most useful kinds of -expressions in expressions statements, and Java does not require a method invocation -used as an expression statement to invoke a void method, so such a trick is -almost never needed. If a trick is needed, either an assignment statement (§15.25) -or a local variable declaration statement (§14.3) can be used instead. -

-

14.8 The if Statement

- -The if statement allows conditional execution of a statement or a conditional -choice of two statements, executing one or the other but not both. -

-The Expression must have type boolean, or a compile-time error occurs. -

-

14.8.1 The if-then Statement

- -An if-then statement is executed by first evaluating the Expression. If evaluation -of the Expression completes abruptly for some reason, the if-then statement -completes abruptly for the same reason. Otherwise, execution continues by making -a choice based on the resulting value: -

-

14.8.2 The if-then-else Statement

- -An if-then-else statement is executed by first evaluating the Expression. If -evaluation of the Expression completes abruptly for some reason, then the if- -then-else statement completes abruptly for the same reason. Otherwise, execution -continues by making a choice based on the resulting value: -

-

14.9 The switch Statement

- -The switch statement transfers control to one of several statements depending on -the value of an expression. -

-The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.

- -The body of a switch statement must be a block. Any statement immediately contained by the block may be labeled with one or more case or default labels. These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.27) in the case labels.

- -All of the following must be true, or a compile-time error will result:

-

-In C and C++ the body of a switch statement can be a statement and statements with case labels do not have to be immediately contained by that statement. Consider the simple loop:

-

for (i = 0; i < n; ++i) foo();
-
-where n is known to be positive. A trick known as Duff's device can be used in C -or C++ to unroll the loop, but this is not valid Java code: -


-int q = (n+7)/8;
-switch (n%8) {
-case 0:			do {		foo();				// Great C hack, Tom,
-case 7:					foo();				// but it's not valid in Java.
-case 6:					foo();
-case 5:					foo();
-case 4:					foo();
-case 3:					foo();
-case 2:					foo();
-case 1:					foo();
-			} while (--q >= 0);
-}
-
-Fortunately, this trick does not seem to be widely known or used. Moreover, it is -less needed nowadays; this sort of code transformation is properly in the province -of state-of-the-art optimizing compilers. -

-When the switch statement is executed, first the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the switch statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the Expression with each case constant. Then there is a choice:

-

-If any statement immediately contained by the Block body of the switch statement completes abruptly, it is handled as follows:

-

-As in C and C++, execution of statements in a switch block "falls through labels" in Java. For example, the program:

-


-class Toomany {
-
-	static void howMany(int k) {
-		switch (k) {
-		case 1:			System.out.print("one ");
-		case 2:			System.out.print("too ");
-		case 3:			System.out.println("many");
-		}
-	}
-
- public static void main(String[] args) { - howMany(3); - howMany(2); - howMany(1); - } -
} -
-contains a switch block in which the code for each case falls through into the code -for the next case. As a result, the program prints: -


-many
-too many
-one too many
-
-If code is not to fall through case to case in this manner, then break statements -should be used, as in this example: -


-class Twomany {
-
-	static void howMany(int k) {
-		switch (k) {
-		case 1:			System.out.println("one");
-					break;					// exit the switch
-		case 2:			System.out.println("two");
-					break;					// exit the switch
-		case 3:			System.out.println("many");
-					break;					// not needed, but good style
-		}
-	}
-
- public static void main(String[] args) { - howMany(1); - howMany(2); - howMany(3); - } -
} -
-This program prints: -


-one
-two
-many
-
-

14.10 The while Statement

- -The while statement executes an Expression and a Statement repeatedly until the -value of the Expression is false. -

-The Expression must have type boolean, or a compile-time error occurs. -

-A while statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the while statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

-

-If the value of the Expression is false the first time it is evaluated, then the -Statement is not executed. -

-

14.10.1 Abrupt Completion

- -Abrupt completion of the contained Statement is handled in the following manner: -

-

14.11 The do Statement

- -The do statement executes a Statement and an Expression repeatedly until the -value of the Expression is false. -

-The Expression must have type boolean, or a compile-time error occurs. -

-A do statement is executed by first executing the Statement. Then there is a choice:

-

-Executing a do statement always executes the contained Statement at least once. -

-

14.11.1 Abrupt Completion

- -Abrupt completion of the contained Statement is handled in the following manner: -

-

14.11.2 Example of do statement

- -The following code is one possible implementation of the toHexString method -(§20.7.14) of class Integer: -


-public static String toHexString(int i) {
-	StringBuffer buf = new StringBuffer(8);
-	do {
-		buf.append(Character.forDigit(i & 0xF, 16));
-		i >>>= 4;
-	} while (i != 0);
-	return buf.reverse().toString();
-}
-
-Because at least one digit must be generated, the do statement is an appropriate -control structure. -

-

14.12 The for Statement

- -The for statement executes some initialization code, then executes an Expression, -a Statement, and some update code repeatedly until the value of the Expression is -false. -

-The Expression must have type boolean, or a compile-time error occurs. -

-

14.12.1 Initialization of for statement

- -A for statement is executed by first executing the ForInit code: -

-

14.12.2 Iteration of for statement

- -Next, a for iteration step is performed, as follows: -

-If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.

- -If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement.

- -

14.12.3 Abrupt Completion of for statement

- -Abrupt completion of the contained Statement is handled in the following manner: -

-

14.13 The break Statement

- -A break statement transfers control out of an enclosing statement. -

-A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement; this statement, which is called the break target, then immediately completes normally. To be precise, a break statement with no label always completes abruptly, the reason being a break with no label. If no switch, while, do, or for statement encloses the break statement, a compile-time error occurs.

- -A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.6) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a while, do, for, or switch statement. To be precise, a break statement with label Identifier always completes abruptly, the reason being a break with label Identifier. If no labeled statement with Identifier as its label encloses the break statement, a compile-time error occurs.

- -It can be seen, then, that a break statement always completes abruptly.

- -The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.18) within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break statement.

- -In the following example, a mathematical graph is represented by an array of arrays. A graph consists of a set of nodes and a set of edges; each edge is an arrow that points from some node to some other node, or from a node to itself. In this example it is assumed that there are no redundant edges; that is, for any two nodes P and Q, where Q may be the same as P, there is at most one edge from P to Q. Nodes are represented by integers, and there is an edge from node i to node edges[i][j] for every i and j for which the array reference edges[i][j] does not throw an IndexOutOfBoundsException.

- -The task of the method loseEdges, given integers i and j, is to construct a new graph by copying a given graph but omitting the edge from node i to node j, if any, and the edge from node j to node i, if any:

-


-class Graph {
-	int edges[][];
-	public Graph(int[][] edges) { this.edges = edges; }
-
-	public Graph loseEdges(int i, int j) {
-		int n = edges.length;
-		int[][] newedges = new int[n][];
-		for (int k = 0; k < n; ++k) {
-
-			edgelist: {
-				int z;
-
-				search: {
-					if (k == i) {
-						for (z = 0; z < edges[k].length; ++z)
-							if (edges[k][z] == j)
-								break search;
-					} else if (k == j) {
-						for (z = 0; z < edges[k].length; ++z)
-							if (edges[k][z] == i)
-								break search;
-					}
-					// No edge to be deleted; share this list.
-					newedges[k] = edges[k];
-					break edgelist;
-				}//search
-				// Copy the list, omitting the edge at position z.
-				int m = edges[k].length - 1;
-				int ne[] = new int[m];
-				System.arraycopy(edges[k], 0, ne, 0, z);
-				System.arraycopy(edges[k], z+1, ne, z, m-z);
-				newedges[k] = ne;
-			}//edgelist
-		}
-		return new Graph(newedges);
-	}
-}
-
-Note the use of two statement labels, edgelist and search, and the use of break -statements. This allows the code that copies a list, omitting one edge, to be shared -between two separate tests, the test for an edge from node i to node j, and the test -for an edge from node j to node i. -

-

14.14 The continue Statement

- -A continue statement may occur only in a while, do, or for statement; statements -of these three kinds are called iteration statements. Control passes to the -loop-continuation point of an iteration statement. -

-A continue statement with no label attempts to transfer control to the innermost enclosing while, do, or for statement; this statement, which is called the continue target, then immediately ends the current iteration and begins a new one. To be precise, such a continue statement always completes abruptly, the reason being a continue with no label. If no while, do, or for statement encloses the continue statement, a compile-time error occurs.

- -A continue statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.6) that has the same Identifier as its label; that statement, which is called the continue target, then immediately ends the current iteration and begins a new one. The continue target must be a while, do, or for statement or a compile-time error occurs. More precisely, a continue statement with label Identifier always completes abruptly, the reason being a continue with label Identifier. If no labeled statement with Identifier as its label contains the continue statement, a compile-time error occurs.

- -It can be seen, then, that a continue statement always completes abruptly.

- -See the descriptions of the while statement (§14.10), do statement (§14.11), and for statement (§14.12) for a discussion of the handling of abrupt termination because of continue.

- -The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.18) within the continue target whose try blocks contain the continue statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the continue target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a continue statement.

- -In the Graph example in the preceding section, one of the break statements is used to finish execution of the entire body of the outermost for loop. This break can be replaced by a continue if the for loop itself is labeled:

-


-class Graph {
-	. . .
-	public Graph loseEdges(int i, int j) {
-		int n = edges.length;
-		int[][] newedges = new int[n][];
-
-		edgelists: for (int k = 0; k < n; ++k) {
-			int z;
-
-			search: {
-				if (k == i) {
-					. . .
-				} else if (k == j) {
-					. . .
-				}
-				newedges[k] = edges[k];
-				continue edgelists;
-			}//search
-			. . .
-		}//edgelists
-		return new Graph(newedges);
-	}
-}
-
-Which to use, if either, is largely a matter of programming style. -

-

14.15 The return Statement

- -A return statement returns control to the invoker of a method (§8.4, §15.11) or -constructor (§8.6, §15.8). -

-A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.6). A compile-time error occurs if a return statement appears within a static initializer (§8.5). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it. To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.

- -A return statement with an Expression must be contained in a method declaration that is declared to return a value (§8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (§5.2) to the declared result type of the method, or a compile-time error occurs.

- -A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.

- -It can be seen, then, that a return statement always completes abruptly.

- -The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.18) within the method or constructor whose try blocks contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

- -

14.16 The throw Statement

- -A throw statement causes an exception (§11) to be thrown. The result is an immediate -transfer of control (§11.3) that may exit multiple statements and multiple -constructor, static and field initializer evaluations, and method invocations until a -try statement (§14.18) is found that catches the thrown value. If no such try -statement is found, then execution of the thread (§17, §20.20) that executed the -throw is terminated (§11.3) after invocation of the UncaughtException method -(§20.21.31) for the thread group to which the thread belongs. -

-The Expression in a throw statement must denote a variable or value of a reference type which is assignable (§5.2) to the type Throwable, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs:

-

-A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the throw statement completes abruptly, the reason being a throw with value V.

- -It can be seen, then, that a throw statement always completes abruptly.

- -If there are any enclosing try statements (§14.18) whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.

- -If a throw statement is contained in a method declaration, but its value is not caught by some try statement that contains it, then the invocation of the method completes abruptly because of the throw.

- -If a throw statement is contained in a constructor declaration, but its value is not caught by some try statement that contains it, then the class instance creation expression (or the method invocation of method newInstance of class Class) that invoked the constructor will complete abruptly because of the throw.

- -If a throw statement is contained in a static initializer (§8.5), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it. If, despite this check, the value is not caught by some try statement that contains the throw statement, then the value is rethrown if it is an instance of class Error or one of its subclasses; otherwise, it is wrapped in an ExceptionInInitializerError object, which is then thrown (§12.4.2).

- -By convention, user-declared throwable types should usually be declared to be subclasses of class Exception, which is a subclass of class Throwable (§11.5, §20.22).

- -

14.17 The synchronized Statement

- -A synchronized statement acquires a mutual-exclusion lock (§17.13) on behalf -of the executing thread, executes a block, then releases the lock. While the executing -thread owns the lock, no other thread may acquire the lock. -

-The type of Expression must be a reference type, or a compile-time error occurs. -

-A synchronized statement is executed by first evaluating the Expression.

- -If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.

- -Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

- -Otherwise, let the non-null value of the Expression be V. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason.

- -Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.

- -The locks acquired by synchronized statements are the same as the locks that are acquired implicitly by synchronized methods; see §8.4.3.5. A single thread may hold a lock more than once. The example:

-


-class Test {
-	public static void main(String[] args) {
-		Test t = new Test();
-		synchronized(t) {
-			synchronized(t) {
-				System.out.println("made it!");
-			}
-		}
-	}
-}
-
-prints: -

made it!
-
-This example would deadlock if a single thread were not permitted to lock a lock -more than once. -

-

14.18 The try statement

- -A try statement executes a block. If a value is thrown and the try statement has -one or more catch clauses that can catch it, then control will be transferred to the -first such catch clause. If the try statement has a finally clause, then another -block of code is executed, no matter whether the try block completes normally or -abruptly, and no matter whether a catch clause is first given control. -

-The following is repeated from §8.4.1 to make the presentation here clearer: -

-The following is repeated from §8.3 to make the presentation here clearer: -

-The Block immediately after the keyword try is called the try block of the try statement. The Block immediately after the keyword finally is called the finally block of the try statement.

- -A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass of Throwable, or a compile-time error occurs. The scope of the parameter variable is the Block of the catch clause. An exception parameter must not have the same name as a local variable or parameter in whose scope it is declared, or a compile-time error occurs.

- -The scope of the name of an exception parameter is the Block of the catch clause. The name of the parameter may not be redeclared as a local variable or exception parameter within the Block of the catch clause; that is, hiding the name of an exception parameter is not permitted.

- -Exception parameters cannot be referred to using qualified names (§6.6), only by simple names.

- -Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its actual argument the thrown exception object.

- -A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.

- -Handling of the finally block is rather complex, so the two cases of a try statement with and without a finally block are described separately.

- -

14.18.1 Execution of try-catch

- -A try statement without a finally block is executed by first executing the try -block. Then there is a choice: -

-In the example: -

class BlewIt extends Exception {
-	BlewIt() { }
-	BlewIt(String s) { super(s); }
-}
-class Test {
-	static void blowUp() throws BlewIt { throw new BlewIt(); }
-	public static void main(String[] args) {
-

-		try {
-			blowUp();
-		} catch (RuntimeException r) {
-			System.out.println("RuntimeException:" + r);
-		} catch (BlewIt b) {
-			System.out.println("BlewIt");
-		}
-	}
-
} -
-the exception BlewIt is thrown by the method blowUp. The try-catch statement -in the body of main has two catch clauses. The run-time type of the exception is -BlewIt which is not assignable to a variable of type RuntimeException, but is -assignable to a variable of type BlewIt, so the output of the example is: -

BlewIt
-
-

14.18.2 Execution of try-catch-finally

- -A try statement with a finally block is executed by first executing the try -block. Then there is a choice: -

-The example: -

class BlewIt extends Exception {
-	BlewIt() { }
-	BlewIt(String s) { super(s); }
-}
-

-class Test {
-
-	static void blowUp() throws BlewIt {
- throw new NullPointerException();
- } - - public static void main(String[] args) { - try { - blowUp(); - } catch (BlewIt b) { - System.out.println("BlewIt"); - } finally { - System.out.println("Uncaught Exception"); - } - } -
} -
-produces the output: -


-Uncaught Exception
-java.lang.NullPointerException
-	at Test.blowUp(Test.java:7)
-	at Test.main(Test.java:11)
-
-The NullPointerException (which is a kind of RuntimeException) that is -thrown by method blowUp is not caught by the try statement in main, because a -NullPointerException is not assignable to a variable of type BlewIt. This -causes the finally clause to execute, after which the thread executing main, -which is the only thread of the test program, terminates because of an uncaught -exception (§20.21.31), which results in printing the exception name and a simple -backtrace. -

-

14.19 Unreachable Statements

- -It is a compile-time error if a statement cannot be executed because it is unreachable -. Every Java compiler must carry out the conservative flow analysis specified -here to make sure all statements are reachable. -

-This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis. For example, a Java compiler will accept the code:

-


-{
-	int n = 5;
-	while (n > 7) n = 2;
-}
-
-even though the value of n is known at compile time and in principle it can be -known at compile time that the assignment to k can never be executed. A Java -compiler must operate according to the rules laid out in this section. -

-The rules in this section define two technical terms:

-

-The definitions here allow a statement to complete normally only if it is reachable. -

-To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."

- -The rules are as follows:

-

-One might expect the if statement to be handled in the following manner, but these are not the rules that Java actually uses:

-

-This approach would be consistent with the treatment of other control structures -in Java. However, in order to allow the if statement to be used conveniently for -"conditional compilation" purposes, the actual rules are as follows: -

-As an example, the following statement results in a compile-time error: -

while (false) { x=3; }
-
-because the statement x=3; is not reachable; but the superficially similar case: -

if (false) { x=3; }
-
-does not result in a compile-time error. An optimizing compiler may realize that -the statement x=3; will never be executed and may choose to omit the code for -that statement from the generated class file, but the statement x=3; is not -regarded as "unreachable" in the technical sense specified here. -

-The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

-

static final boolean DEBUG = false;
-
-and then write code such as: -

if (DEBUG) { x=3; }
-
-The idea is that it should be possible to change the value of DEBUG from false to -true or from true to false and then compile the code correctly with no other -changes to the program text. -

-This ability to "conditionally compile" has a significant impact on, and relationship to, binary compatibility (§13). If a set of classes that use such a "flag" variable are compiled and conditional code is omitted, it does not suffice later to distribute just a new version of the class or interface that contains the definition of the flag. A change to the value of a flag is, therefore, not binary compatible with preexisting binaries (§13.4.8). (There are other reasons for such incompatibility as well, such as the use of constants in case labels in switch statements; see §13.4.8.)

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- - -


- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - -The Java Language Specification - Expressions - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-



- - -

-CHAPTER - 15

- -

Expressions

-

- -Much of the work in a Java program is done by evaluating expressions, either -for their side effects, such as assignments to variables, or for their values, which -can be used as arguments or operands in larger expressions, or to affect the execution -sequence in statements, or both. -

-This chapter specifies the meanings of Java expressions and the rules for their evaluation.

- -

15.1 Evaluation, Denotation, and Result

- -When an expression in a Java program is evaluated (executed), the result denotes -one of three things: -

-Evaluation of an expression can also produce side effects, because expressions may contain embedded assignments, increment operators, decrement operators, and method invocations.

- -An expression denotes nothing if and only if it is a method invocation (§15.11) that invokes a method that does not return a value, that is, a method declared void (§8.4). Such an expression can be used only as an expression statement (§14.7), because every other context in which an expression can appear requires the expression to denote something. An expression statement that is a method invocation may also invoke a method that produces a result; in this case the value returned by the method is quietly discarded.

- -Each expression occurs in the declaration of some (class or interface) type that is being declared: in a field initializer, in a static initializer, in a constructor declaration, or in the code for a method.

- -

15.2 Variables as Values

- -If an expression denotes a variable, and a value is required for use in further evaluation, -then the value of that variable is used. In this context, if the expression -denotes a variable or a value, we may speak simply of the value of the expression. -

-

15.3 Type of an Expression

- -If an expression denotes a variable or a value, then the expression has a type -known at compile time. The rules for determining the type of an expression are -explained separately below for each kind of expression. -

-The value of an expression is always assignment compatible (§5.2) with the type of the expression, just as the value stored in a variable is always compatible with the type of the variable. In other words, the value of an expression whose type is T is always suitable for assignment to a variable of type T.

- -Note that an expression whose type is a class type F that is declared final is guaranteed to have a value that is either a null reference or an object whose class is F itself, because final types have no subclasses.

- -

15.4 Expressions and Run-Time Checks

- -If the type of an expression is a primitive type, then the value of the expression is -of that same primitive type. But if the type of an expression is a reference type, -then the class of the referenced object, or even whether the value is a reference to -an object rather than null, is not necessarily known at compile time. There are a -few places in the Java language where the actual class of a referenced object -affects program execution in a manner that cannot be deduced from the type of the -expression. They are as follows: -

-The first two of the cases just listed ought never to result in detecting a type error. -Thus, a Java run-time type error can occur only in these situations: -

-

15.5 Normal and Abrupt Completion of Evaluation

- -Every expression has a normal mode of evaluation in which certain computational -steps are carried out. The following sections describe the normal mode of evaluation -for each kind of expression. If all the steps are carried out without an exception -being thrown, the expression is said to complete normally. -

-If, however, evaluation of an expression throws an exception, then the expression is said to complete abruptly. An abrupt completion always has an associated reason, which is always a throw with a given value.

- -Run-time exceptions are thrown by the predefined operators as follows:

-

-A method invocation expression can also result in an exception being thrown if an -exception occurs that causes execution of the method body to complete abruptly. -A class instance creation expression can also result in an exception being thrown -if an exception occurs that causes execution of the constructor to complete -abruptly. Various linkage and virtual machine errors may also occur during the -evaluation of an expression. By their nature, such errors are difficult to predict and -difficult to handle. -

-If an exception occurs, then evaluation of one or more expressions may be terminated before all steps of their normal mode of evaluation are complete; such expressions are said to complete abruptly. The terms "complete normally" and "complete abruptly" are also applied to the execution of statements (§14.1). A statement may complete abruptly for a variety of reasons, not just because an exception is thrown.

- -If evaluation of an expression requires evaluation of a subexpression, abrupt completion of the subexpression always causes the immediate abrupt completion of the expression itself, with the same reason, and all succeeding steps in the normal mode of evaluation are not performed.

- -

15.6 Evaluation Order

- -Java guarantees that the operands of operators appear to be evaluated in a specific -evaluation order, namely, from left to right. -

-It is recommended that Java code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

- -

15.6.1 Evaluate Left-Hand Operand First

- -The left-hand operand of a binary operator appears to be fully evaluated before -any part of the right-hand operand is evaluated. For example, if the left-hand operand -contains an assignment to a variable and the right-hand operand contains a -reference to that same variable, then the value produced by the reference will -reflect the fact that the assignment occurred first. -

-Thus:

-


-class Test {
-	public static void main(String[] args) {
-		int i = 2;
-		int j = (i=3) * i;
-		System.out.println(j);
-	}
-}
-
-prints: -

9
-
-It is not permitted for it to print 6 instead of 9. -

-If the operator is a compound-assignment operator (§15.25.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied combining operation. So, for example, the test program:

-


-class Test {
-	public static void main(String[] args) {
-		int a = 9;
-		a += (a = 3);									// first example
-		System.out.println(a);
-		int b = 9;
-		b = b + (b = 3);									// second example
-		System.out.println(b);
-	}
-}
-
-prints: -


-12
-12
-
-because the two assignment statements both fetch and remember the value of the -left-hand operand, which is 9, before the right-hand operand of the addition is -evaluated, thereby setting the variable to 3. It is not permitted for either example -to produce the result 6. Note that both of these examples have unspecified behavior -in C, according to the ANSI/ISO standard. -

-If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand appears to have been evaluated.

- -Thus, the test program:

-


-class Test {
-
-	public static void main(String[] args) {
-
-		int j = 1;
-
-		try {
-			int i = forgetIt() / (j = 2);
-		} catch (Exception e) {
-			System.out.println(e);
-			System.out.println("Now j = " + j);
-		}
-	}
-
-	static int forgetIt() throws Exception {
-		throw new Exception("I'm outta here!");
-	}
-}
-
-prints: -


-java.lang.Exception: I'm outta here!
-Now j = 1
-
-because the left-hand operand forgetIt() of the operator / throws an exception -before the right-hand operand and its embedded assignment of 2 to j occurs. -

-

15.6.2 Evaluate Operands before Operation

- -Java also guarantees that every operand of an operator (except the conditional -operators &&, ||, and ? :) appears to be fully evaluated before any part of the -operation itself is performed. -

-If the binary operator is an integer division / (§15.16.2) or integer remainder % (§15.16.3), then its execution may raise an ArithmeticException, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.

- -So, for example, the program:

-


-class Test {
-
-	public static void main(String[] args) {
-		int divisor = 0;
-		try {
-			int i = 1 / (divisor * loseBig());
-		} catch (Exception e) {
-			System.out.println(e);
-		}
-	}
-
- static int loseBig() throws Exception { - throw new Exception("Shuffle off to Buffalo!"); - } -
} -
-always prints: -

java.lang.Exception: Shuffle off to Buffalo!
-
-and not: -

java.lang.ArithmeticException: / by zero
-
-since no part of the division operation, including signaling of a divide-by-zero -exception, may appear to occur before the invocation of loseBig completes, even -though the implementation may be able to detect or infer that the division operation -would certainly result in a divide-by-zero exception. -

-

15.6.3 Evaluation Respects Parentheses and Precedence

- -Java implementations must respect the order of evaluation as indicated explicitly -by parentheses and implicitly by operator precedence. An implementation may -not take advantage of algebraic identities such as the associative law to rewrite -expressions into a more convenient computational order unless it can be proven -that the replacement expression is equivalent in value and in its observable side -effects, even in the presence of multiple threads of execution (using the thread -execution model in §17), for all possible computational values that might be -involved. -

-In the case of floating-point calculations, this rule applies also for infinity and not-a-number (NaN) values. For example, !(x<y) may not be rewritten as x>=y, because these expressions have different values if either x or y is NaN.

- -Specifically, floating-point calculations that appear to be mathematically associative are unlikely to be computationally associative. Such computations must not be naively reordered. For example, it is not correct for a Java compiler to rewrite 4.0*x*0.5 as 2.0*x; while roundoff happens not to be an issue here, there are large values of x for which the first expression produces infinity (because of overflow) but the second expression produces a finite result.

- -So, for example, the test program:

-


-class Test {
-
-	public static void main(String[] args) {
-		double d = 8e+307;
-		System.out.println(4.0 * d * 0.5);
-		System.out.println(2.0 * d);
-	}
-}
-
-prints: -


-Infinity
-1.6e+308
-
-because the first expression overflows and the second does not. -

-In contrast, integer addition and multiplication are provably associative in Java; for example a+b+c, where a, b, and c are local variables (this simplifying assumption avoids issues involving multiple threads and volatile variables), will always produce the same answer whether evaluated as (a+b)+c or a+(b+c); if the expression b+c occurs nearby in the code, a smart compiler may be able to use this common subexpression.

- -

15.6.4 Argument Lists are Evaluated Left-to-Right

- -In a method or constructor invocation or class instance creation expression, argument -expressions may appear within the parentheses, separated by commas. Each -argument expression appears to be fully evaluated before any part of any argument -expression to its right. -

-Thus:

-

class Test {
-

-	public static void main(String[] args) {
-		String s = "going, ";
-		print3(s, s, s = "gone");
-	}
-
-	static void print3(String a, String b, String c) {
-		System.out.println(a + b + c);
-	}
-}
-
-always prints: -

going, going, gone
-
-because the assignment of the string "gone" to s occurs after the first two arguments -to print3 have been evaluated. -

-If evaluation of an argument expression completes abruptly, no part of any argument expression to its right appears to have been evaluated.

- -Thus, the example:

-


-class Test {
-	static int id;
-	public static void main(String[] args) {
-		try {
-			test(id = 1, oops(), id = 3);
-		} catch (Exception e) {
-			System.out.println(e + ", id=" + id);
-		}
-	}
-
static int oops() throws Exception { - throw new Exception("oops"); - } -
static int test(int a, int b, int c) { - return a + b + c; - } -
} -
-prints: -

java.lang.Exception: oops, id=1
-
-because the assignment of 3 to id is not executed. -

-

15.6.5 Evaluation Order for Other Expressions

- -The order of evaluation for some expressions is not completely covered by these -general rules, because these expressions may raise exceptional conditions at times -that must be specified. See, specifically, the detailed explanations of evaluation -order for the following kinds of expressions: -

-

15.7 Primary Expressions

- -Primary expressions include most of the simplest kinds of expressions, from -which all others are constructed: literals, field accesses, method invocations, and -array accesses. A parenthesized expression is also treated syntactically as a primary -expression. -

-As programming language grammars go, this part of the Java grammar is unusual, in two ways. First, one might expect simple names, such as names of local variables and method parameters, to be primary expressions. For technical reasons, names are lumped together with primary expressions a little later when postfix expressions are introduced (§15.13).

- -The technical reasons have to do with allowing left-to-right parsing of Java programs with only one-token lookahead. Consider the expressions (z[3]) and (z[]). The first is a parenthesized array access (§15.12) and the second is the start of a cast (§15.15). At the point that the look-ahead symbol is [, a left-to-right parse will have reduced the z to the nonterminal Name. In the context of a cast we prefer not to have to reduce the name to a Primary, but if Name were one of the alternatives for Primary, then we could not tell whether to do the reduction (that is, we could not determine whether the current situation would turn out to be a parenthesized array access or a cast) without looking ahead two tokens, to the token following the [. The Java grammar presented here avoids the problem by keeping Name and Primary separate and allowing either in certain other syntax rules (those for MethodInvocation, ArrayAccess, PostfixExpression, but not for FieldAccess, because this is covered by Name). This strategy effectively defers the question of whether a Name should be treated as a Primary until more context can be examined. (Other problems remain with cast expressions; see §19.1.5.)

- -The second unusual feature avoids a potential grammatical ambiguity in the expression:

-

new int[3][3]
-
-which in Java always means a single creation of a multidimensional array, but -which, without appropriate grammatical finesse, might also be interpreted as -meaning the same as: -

(new int[3])[3]
-
-This ambiguity is eliminated by splitting the expected definition of Primary into -Primary and PrimaryNoNewArray. (This may be compared to the splitting of -Statement into Statement and StatementNoShortIf (§14.4) to avoid the "dangling -else" problem.) -

-

15.7.1 Literals

- -A literal (§3.10) denotes a fixed, unchanging value. -

-The following production from §3.10 is repeated here for convenience:

-

-The type of a literal is determined as follows:

-

-Evaluation of a literal always completes normally.

- -

15.7.2 this

- -The keyword this may be used only in the body of an instance method or constructor, -or in the initializer of an instance variable of a class. If it appears anywhere -else, a compile-time error occurs. -

-When used as a primary expression, the keyword this denotes a value, that is a reference to the object for which the instance method was invoked (§15.11), or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.

- -In the example:

-


-class IntVector {
-	int[] v;
-	boolean equals(IntVector other) {
-		if (this == other)
-			return true;
-		if (v.length != other.v.length)
-			return false;
-		for (int i = 0; i < v.length; i++)
-			if (v[i] != other.v[i])
-				return false;
-		return true;
-	}
-
} -
-the class IntVector implements a method equals, which compares two vectors. -If the other vector is the same vector object as the one for which the equals -method was invoked, then the check can skip the length and value comparisons. -The equals method implements this check by comparing the reference to the -other object to this. -

-The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body (§8.6.5).

- -

15.7.3 Parenthesized Expressions

- -A parenthesized expression is a primary expression whose type is the type of the -contained expression and whose value at run time is the value of the contained -expression. -

-

15.8 Class Instance Creation Expressions

- -A class instance creation expression is used to create new objects that are -instances of classes. -

-In a class instance creation expression, the ClassType must name a class that is not abstract. This class type is the type of the creation expression.

- -The arguments in the argument list, if any, are used to select a constructor declared in the body of the named class type, using the same matching rules as for method invocations (§15.11). As in method invocations, a compile-time method matching error results if there is no unique constructor that is both applicable to the provided arguments and the most specific of all the applicable constructors.

- -

15.8.1 Run-time Evaluation of Class Instance Creation Expressions

- -At run time, evaluation of a class instance creation expression is as follows. -

-First, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (§15.8.2).

- -The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its standard default value (§4.5.4).

- -Next, the argument list is evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.

- -Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.6) and is described in detail in §12.5.

- -The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.

- -

15.8.2 Example: Evaluation Order and Out-of-Memory Detection

- -If evaluation of a class instance creation expression finds there is insufficient -memory to perform the creation operation, then an OutOfMemoryError is thrown. -This check occurs before any argument expressions are evaluated. -

-So, for example, the test program:

-


-class List {
-	int value;
-	List next;
-	static List head = new List(0);
-	List(int n) { value = n; next = head; head = this; }
-}
-
-class Test {
-	public static void main(String[] args) {
-		int id = 0, oldid = 0;
-		try {
-			for (;;) {
-				++id;
-				new List(oldid = id);
-			}
-		} catch (Error e) {
-			System.out.println(e + ", " + (oldid==id));
-		}
-	}
-}
-
-prints: -

java.lang.OutOfMemoryError: List, false
-
-because the out-or-memory condition is detected before the argument expression -oldid = id is evaluated. -

-Compare this to the treatment of array creation expressions (§15.9), for which the out-of-memory condition is detected after evaluation of the dimension expressions (§15.9.3).

- -

15.9 Array Creation Expressions

- -An array instance creation expression is used to create new arrays (§10). -

-An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or TypeName. The TypeName may name any reference type, even an abstract class type (§8.1.2.1) or an interface type (§9).

- -The type of the creation expression is an array type that can denoted by a copy of the creation expression from which the new keyword and every DimExpr expression have been deleted; for example, the type of the creation expression:

-

new double[3][3][]
-
-is: -

double[][][]
-
-The type of each dimension expression DimExpr must be an integral type, or a compile-time error occurs. Each expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs; this means, specifically, that the type of a dimension expression must not be long.

- -

15.9.1 Run-time Evaluation of Array Creation Expressions

- -At run time, evaluation of an array creation expression behaves as follows. -

-First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.

- -Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then an NegativeArraySizeException is thrown.

- -Next, space is allocated for the new array. If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an OutOfMemoryError.

- -Then, if a single DimExpr appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its standard default value (§4.5.4).

- -If an array creation expression contains N DimExpr expressions, then it effectively executes a set of nested loops of depth to create the implied arrays of arrays. For example, the declaration:

-

float[][] matrix = new float[3][3];
-
-is equivalent in behavior to: -


-float[][] matrix = new float[3][];
-for (int d = 0; d < matrix.length; d++)
-	matrix[d] = new float[3];
-
-and: -

Age[][][][][] Aquarius = new Age[6][10][8][12][];
-
-is equivalent to: -


-Age[][][][][] Aquarius = new Age[6][][][][];
-for (int d1 = 0; d1 < Aquarius.length; d1++) {
-	Aquarius[d1] = new Age[8][][][];
-	for (int d2 = 0; d2 < Aquarius[d1].length; d2++) {
-		Aquarius[d1][d2] = new Age[10][][];
-		for (int d3 = 0; d3 < Aquarius[d1][d2].length; d3++) {
-			Aquarius[d1][d2][d3] = new Age[12][];
-		}
-	}
-}
-
-with d, d1, d2 and d3 replaced by names that are not already locally declared. -Thus, a single new expression actually creates one array of length 6, 6 arrays of -length 10, arrays of length 8, and arrays of length -12. This example leaves the fifth dimension, which would be arrays containing the -actual array elements (references to Age objects), initialized only to null references. -These arrays can be filled in later by other code, such as: -


-Age[] Hair = { new Age("quartz"), new Age("topaz") };
-Aquarius[1][9][6][9] = Hair;
-
-A multidimensional array need not have arrays of the same length at each level; thus, a triangular matrix may be created by:

-


-float triang[][] = new float[100][];
-for (int i = 0; i < triang.length; i++)
-	triang[i] = new float[i+1];
-
-There is, however, no way to get this effect with a single creation expression. -

-

15.9.2 Example: Array Creation Evaluation Order

- -In an array creation expression (§15.9), there may be one or more dimension -expressions, each within brackets. Each dimension expression is fully evaluated -before any part of any dimension expression to its right. -

-Thus:

-


-class Test {
-	public static void main(String[] args) {
-		int i = 4;
-		int ia[][] = new int[i][i=3];
-		System.out.println(
-			"[" + ia.length + "," + ia[0].length + "]");
-	}
-}
-
-prints: -

[4,3]
-
-because the first dimension is calculated as 4 before the second dimension expression -sets i to 3. -

-If evaluation of a dimension expression completes abruptly, no part of any dimension expression to its right will appear to have been evaluated. Thus, the example:

-


-class Test {
-
-	public static void main(String[] args) {
-		int[][] a = { { 00, 01 }, { 10, 11 } };
-		int i = 99;
-		try {
-			a[val()][i = 1]++;
-		} catch (Exception e) {
-			System.out.println(e + ", i=" + i);
-		}
-	}
-
static int val() throws Exception { - throw new Exception("unimplemented"); - } -
} -
-prints: -

java.lang.Exception: unimplemented, i=99
-
-because the embedded assignment that sets i to 1 is never executed. -

-

15.9.3 Example: Array Creation and Out-of-Memory Detection

- -If evaluation of an array creation expression finds there is insufficient memory to -perform the creation operation, then an OutOfMemoryError is thrown. This check -occurs only after evaluation of all dimension expressions has completed normally. -

-So, for example, the test program:

-


-class Test {
-	public static void main(String[] args) {
-		int len = 0, oldlen = 0;
-		Object[] a = new Object[0];
-		try {
-			for (;;) {
-				++len;
-				Object[] temp = new Object[oldlen = len];
-				temp[0] = a;
-				a = temp;
-			}
-		} catch (Error e) {
-			System.out.println(e + ", " + (oldlen==len));
-		}
-	}
-}
-
-prints: -

java.lang.OutOfMemoryError, true
-
-because the out-of-memory condition is detected after the argument expression -oldlen = len is evaluated. -

-Compare this to class instance creation expressions (§15.8), which detect the out-of-memory condition before evaluating argument expressions (§15.8.2).

- -

15.10 Field Access Expressions

- -A field access expression may access a field of an object or array, a reference to -which is the value of either an expression or the special keyword super. (It is also -possible to refer to a field of the current instance or current class by using a simple -name; see §15.13.1.) -

-The meaning of a field access expression is determined using the same rules as for qualified names (§6.6), but limited by the fact that an expression cannot denote a package, class type, or interface type.

- -

15.10.1 Field Access Using a Primary

- -The type of the Primary must be a reference type T, or a compile-time error -occurs. The meaning of the field access expression is determined as follows: -

-Note, specifically, that only the type of the Primary expression, not the class of the -actual object referred to at run time, is used in determining which field to use. -

-Thus, the example:

-

class S { int x = 0; }
-class T extends S { int x = 1; }
-class Test {
-	public static void main(String[] args) {
-

-		T t = new T();
-		System.out.println("t.x=" + t.x + when("t", t));
-
-		S s = new S();
-		System.out.println("s.x=" + s.x + when("s", s));
-
-		s = t;
-		System.out.println("s.x=" + s.x + when("s", s));
-
} -
- static String when(String name, Object t) { - return " when " + name + " holds a " - + t.getClass() + " at run time."; - } -} -
-produces the output: -


-t.x=1 when t holds a class T at run time.
-s.x=0 when s holds a class S at run time.
-s.x=0 when s holds a class T at run time.
-
-The last line shows that, indeed, the field that is accessed does not depend on the -run-time class of the referenced object; even if s holds a reference to an object of -class T, the expression s.x refers to the x field of class S, because the type of the -expression s is S. Objects of class T contain two fields named x, one for class T -and one for its superclass S. -

-This lack of dynamic lookup for field accesses allows Java to run efficiently with straightforward implementations. The power of late binding and overriding is available in Java, but only when instance methods are used. Consider the same example using instance methods to access the fields:

-

class S { int x = 0; int z() { return x; } }
-class T extends S { int x = 1; int z() { return x; } }
-class Test {
-

-	public static void main(String[] args) {
-		T t = new T();
-		System.out.println("t.z()=" + t.z() + when("t", t));
-		S s = new S();
-		System.out.println("s.z()=" + s.z() + when("s", s));
-		s = t;
-		System.out.println("s.z()=" + s.z() + when("s", s));
-	}
-
-	static String when(String name, Object t) {
-		return " when " + name + " holds a "
-			+ t.getClass() + " at run time.";
-	}
-}
-
-Now the output is: -


-t.z()=1 when t holds a class T at run time.
-s.z()=0 when s holds a class S at run time.
-s.z()=1 when s holds a class T at run time.
-
-The last line shows that, indeed, the method that is accessed does depend on the -run-time class of referenced object; when s holds a reference to an object of class -T, the expression s.z() refers to the z method of class T, despite the fact that the -type of the expression s is S. Method z of class T overrides method z of class S. -

-The following example demonstrates that a null reference may be used to access a class (static) variable without causing an exception:

-


-class Test {
-	static String mountain = "Chocorua";
-
-	static Test favorite(){
-		System.out.print("Mount ");
-		return null;
-	}
-
-	public static void main(String[] args) {
-		System.out.println(favorite().mountain);
-	}
-}
-
-It compiles, executes, and prints: -

Mount Chocorua
-
-Even though the result of favorite() is null, a NullPointerException is not -thrown. That "Mount " is printed demonstrates that the Primary expression is -indeed fully evaluated at run time, despite the fact that only its type, not its value, -is used to determine which field to access (because the field mountain is static). -

-

15.10.2 Accessing Superclass Members using super

- -The special form using the keyword super is valid only in an instance method or -constructor, or in the initializer of an instance variable of a class; these are exactly -the same situations in which the keyword this may be used (§15.7.2). The form -involving super may not be used anywhere in the class Object, since Object has -no superclass; if super appears in class Object, then a compile-time error results. -

-Suppose that a field access expression super.name appears within class C, and the immediate superclass of C is class S. Then super.name is treated exactly as if it had been the expression ((S)this).name; thus, it refers to the field named name of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named name that is visible in class S, even if that field is hidden by a declaration of a field named name in class C.

- -The use of super is demonstrated by the following example:

-


-interface I { int x = 0; }
-class T1 implements I { int x = 1; }
-class T2 extends T1 { int x = 2; }
-class T3 extends T2 {
-	int x = 3;
-	void test() {
-		System.out.println("x=\t\t"+x);
-		System.out.println("super.x=\t\t"+super.x);
-		System.out.println("((T2)this).x=\t"+((T2)this).x);
-		System.out.println("((T1)this).x=\t"+((T1)this).x);
-		System.out.println("((I)this).x=\t"+((I)this).x);
-	}
-}
-class Test {
-	public static void main(String[] args) {
-		new T3().test();
-	}
-}
-
-which produces the output: -


-x=					3
-super.x=					2
-((T2)this).x=					2
-((T1)this).x=					1
-((I)this).x=					0
-
-Within class T3, the expression super.x is treated exactly as if it were: -

((T2)this).x
-
-

15.11 Method Invocation Expressions

- -A method invocation expression is used to invoke a class or instance method. -

-The definition of ArgumentList from §15.8 is repeated here for convenience: -

-Resolving a method name at compile time is more complicated than resolving a field name because of the possibility of method overloading. Invoking a method at run time is also more complicated than accessing a field because of the possibility of instance method overriding.

- -Determining the method that will be invoked by a method invocation expression involves several steps. The following three sections describe the compile-time processing of a method invocation; the determination of the type of the method invocation expression is described in §15.11.3.

- -

15.11.1 Compile-Time Step 1: Determine Class or Interface to Search

- -The first step in processing a method invocation at compile time is to figure out -the name of the method to be invoked and which class or interface to check for -definitions of methods of that name. There are several cases to consider, depending -on the form that precedes the left parenthesis, as follows: -

-

15.11.2 Compile-Time Step 2: Determine Method Signature

- -The second step searches the class or interface determined in the previous step for -method declarations. This step uses the name of the method and the types of the -argument expressions to locate method declarations that are both applicable and -accessible, that is, declarations that can be correctly invoked on the given arguments. -There may be more than one such method declaration, in which case the -most specific one is chosen. The descriptor (signature plus return type) of the most -specific method declaration is one used at run time to do the method dispatch. -

-

15.11.2.1 Find Methods that are Applicable and Accessible

- -A method declaration is applicable to a method invocation if and only if both of -the following are true: -

-The class or interface determined by the process described in §15.11.1 is searched for all method declarations applicable to this method invocation; method definitions inherited from superclasses and superinterfaces are included in this search.

- -Whether a method declaration is accessible to a method invocation depends on the access modifier (public, none, protected, or private) in the method declaration and on where the method invocation appears.

- -If the class or interface has no method declaration that is both applicable and accessible, then a compile-time error occurs.

- -In the example program:

-


-public class Doubler {
-	static int two() { return two(1); }
-	private static int two(int i) { return 2*i; }
-}
-
-class Test extends Doubler {	
-	public static long two(long j) {return j+j; }
-
-	public static void main(String[] args) {
-		System.out.println(two(3));
-		System.out.println(Doubler.two(3)); // compile-time error
-	}
-}
-
-for the method invocation two(1) within class Doubler, there are two accessible -methods named two, but only the second one is applicable, and so that is the one -invoked at run time. For the method invocation two(3) within class Test, there -are two applicable methods, but only the one in class Test is accessible, and so -that is the one to be invoked at run time (the argument 3 is converted to type -long). For the method invocation Doubler.two(3), the class Doubler, not class -Test, is searched for methods named two; the only applicable method is not -accessible, and so this method invocation causes a compile-time error. -

-Another example is:

-


-class ColoredPoint {
-	int x, y;
-	byte color;
-	void setColor(byte color) { this.color = color; }
-}
-
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint cp = new ColoredPoint();
-		byte color = 37;
-		cp.setColor(color);
-		cp.setColor(37);											// compile-time error
-	}
-}
-
-Here, a compile-time error occurs for the second invocation of setColor, because -no applicable method can be found at compile time. The type of the literal 37 is -int, and int cannot be converted to byte by method invocation conversion. -Assignment conversion, which is used in the initialization of the variable color, -performs an implicit conversion of the constant from type int to byte, which is -permitted because the value 37 is small enough to be represented in type byte; but -such a conversion is not allowed for method invocation conversion. -

-If the method setColor had, however, been declared to take an int instead of a byte, then both method invocations would be correct; the first invocation would be allowed because method invocation conversion does permit a widening conversion from byte to int. However, a narrowing cast would then be required in the body of setColor:

-

	void setColor(int color) { this.color = (byte)color; }
-
-

15.11.2.2 Choose the Most Specific Method

- -If more than one method is both accessible and applicable to a method invocation, -it is necessary to choose one to provide the descriptor for the run-time method dispatch. -Java uses the rule that the most specific method is chosen. -

-The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

- -The precise definition is as follows. Let m be a name and suppose that there are two declarations of methods named m, each having n parameters. Suppose that one declaration appears within a class or interface T and that the types of the parameters are T1, . . . , Tn; suppose moreover that the other declaration appears within a class or interface U and that the types of the parameters are U1, . . . , Un. Then the method m declared in T is more specific than the method m declared in U if and only if both of the following are true:

-

-A method is said to be maximally specific for a method invocation if it is applicable and accessible and there is no other applicable and accessible method that is more specific.

- -If there is exactly one maximally specific method, then it is in fact the most specific method; it is necessarily more specific than any other method that is applicable and accessible. It is then subjected to some further compile-time checks as described in §15.11.3.

- -It is possible that no method is the most specific, because there are two or more maximally specific method declarations. In this case, we say that the method invocation is ambiguous, and a compile-time error occurs.

- -

15.11.2.3 Example: Overloading Ambiguity

- -Consider the example: -

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-

-class Test {
-
-	static void test(ColoredPoint p, Point q) {
-		System.out.println("(ColoredPoint, Point)");
-	}
-
-	static void test(Point p, ColoredPoint q) {
-		System.out.println("(Point, ColoredPoint)");
-	}
-
-	public static void main(String[] args) {
-		ColoredPoint cp = new ColoredPoint();
-		test(cp, cp);											// compile-time error
-	}
-}
-
-This example produces an error at compile time. The problem is that there are two -declarations of test that are applicable and accessible, and neither is more specific -than the other. Therefore, the method invocation is ambiguous. -

-If a third definition of test were added:

-


-	static void test(ColoredPoint p, ColoredPoint q) {
-		System.out.println("(ColoredPoint, ColoredPoint)");
-	}
-
-then it would be more specific than the other two, and the method invocation -would no longer be ambiguous. -

-

15.11.2.4 Example: Return Type Not Considered

- -As another example, consider: -

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-class Test {
-

-	static int test(ColoredPoint p) {
-		return color;
-	}
-
-	static String test(Point p) {
-		return "Point";
-	}
-
-	public static void main(String[] args) {
-		ColoredPoint cp = new ColoredPoint();
-		String s = test(cp);											// compile-time error
-	}
-}
-
-Here the most specific declaration of method test is the one taking a parameter -of type ColoredPoint. Because the result type of the method is int, a compile- -time error occurs because an int cannot be converted to a String by assignment -conversion. This example shows that, in Java, the result types of methods do not -participate in resolving overloaded methods, so that the second test method, -which returns a String, is not chosen, even though it has a result type that would -allow the example program to compile without error. -

-

15.11.2.5 Example: Compile-Time Resolution

- -The most applicable method is chosen at compile time; its descriptor determines -what method is actually executed at run time. If a new method is added to a class, -then Java code that was compiled with the old definition of the class might not use -the new method, even if a recompilation would cause this method to be chosen. -

-So, for example, consider two compilation units, one for class Point:

-

package points;
-public class Point {
-	public int x, y;
-	public Point(int x, int y) { this.x = x; this.y = y; }
-	public String toString() { return toString(""); }
-

-	public String toString(String s) {
-		return "(" + x + "," + y + s + ")";
-	}
-}
-
-and one for class ColoredPoint: -

package points;
-public class ColoredPoint extends Point {
-

-	public static final int
-		RED = 0, GREEN = 1, BLUE = 2;
-
-	public static String[] COLORS =
-		{ "red", "green", "blue" };
-	public byte color;
-
-	public ColoredPoint(int x, int y, int color) {
-		super(x, y); this.color = (byte)color;
-	}
-
-	/** Copy all relevant fields of the argument into
-		    this ColoredPoint object. */
-	public void adopt(Point p) { x = p.x; y = p.y; }
-
-	public String toString() {
-		String s = "," + COLORS[color];
-		return super.toString(s);
-	}
-}
-
-Now consider a third compilation unit that uses ColoredPoint: -

import points.*;
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint cp =
-			new ColoredPoint(6, 6, ColoredPoint.RED);
-		ColoredPoint cp2 =
-			new ColoredPoint(3, 3, ColoredPoint.GREEN);
-		cp.adopt(cp2);
-		System.out.println("cp: " + cp);
-	}
-}
-
-The output is: -

cp: (3,3,red)
-
-The application programmer who coded class Test has expected to see the word green, because the actual argument, a ColoredPoint, has a color field, and color would seem to be a "relevant field" (of course, the documentation for the package Points ought to have been much more precise!).

- -Notice, by the way, that the most specific method (indeed, the only applicable method) for the method invocation of adopt has a signature that indicates a method of one parameter, and the parameter is of type Point. This signature becomes part of the binary representation of class Test produced by the compiler and is used by the method invocation at run time.

- -Suppose the programmer reported this software error and the maintainer of the points package decided, after due deliberation, to correct it by adding a method to class ColoredPoint:

-


-public void adopt(ColoredPoint p) {
-	adopt((Point)p); color = p.color;
-}
-
-If the application programmer then runs the old binary file for Test with the new binary file for ColoredPoint, the output is still:

-

cp: (3,3,red)
-
-because the old binary file for Test still has the descriptor "one parameter, whose -type is Point; void" associated with the method call cp.adopt(cp2). If the -source code for Test is recompiled, the compiler will then discover that there are -now two applicable adopt methods, and that the signature for the more specific -one is "one parameter, whose type is ColoredPoint; void"; running the program -will then produce the desired output: -

cp: (3,3,green)
-
-With forethought about such problems, the maintainer of the points package could fix the ColoredPoint class to work with both newly compiled and old code, by adding defensive code to the old adopt method for the sake of old code that still invokes it on ColoredPoint arguments:

-


-public void adopt(Point p) {
-	if (p instanceof ColoredPoint)
-		color = ((ColoredPoint)p).color;
-	x = p.x; y = p.y;
-}
-
-A similar consideration applies if a method is to be moved from a class to a superclass. In this case a forwarding method can be left behind for the sake of old code. The maintainer of the points package might choose to move the adopt method that takes a Point argument up to class Point, so that all Point objects may enjoy the adopt functionality. To avoid compatibility problems with old binary code, the maintainer should leave a forwarding method behind in class ColoredPoint:

-


-public void adopt(Point p) {
-	if (p instanceof ColoredPoint)
-		color = ((ColoredPoint)p).color;
-	super.adopt(p);
-}
-
-Ideally, Java code should be recompiled whenever code that it depends on is changed. However, in an environment where different Java classes are maintained by different organizations, this is not always feasible. Defensive programming with careful attention to the problems of class evolution can make upgraded code much more robust. See §13 for a detailed discussion of binary compatibility and type evolution.

- -

15.11.3 Compile-Time Step 3: Is the Chosen Method Appropriate?

- -If there is a most specific method declaration for a method invocation, it is called -the compile-time declaration for the method invocation. Two further checks must -be made on the compile-time declaration: -

-The following compile-time information is then associated with the method invocation for use at run time:

-

-If the compile-time declaration for the method invocation is not void, then the type of the method invocation expression is the result type specified in the compile-time declaration.

- -

15.11.4 Runtime Evaluation of Method Invocation

- -At run time, method invocation requires five steps. First, a target reference may be -computed. Second, the argument expressions are evaluated. Third, the accessibility -of the method to be invoked is checked. Fourth, the actual code for the method -to be executed is located. Fifth, a new activation frame is created, synchronization -is performed if necessary, and control is transferred to the method code. -

-

15.11.4.1 Compute Target Reference (If Necessary)

- -There are several cases to consider, depending on which of the three productions -for MethodInvocation (§15.11) is involved: -

-

15.11.4.2 Evaluate Arguments

- -The argument expressions are evaluated in order, from left to right. If the evaluation -of any argument expression completes abruptly, then no part of any argument -expression to its right appears to have been evaluated, and the method invocation -completes abruptly for the same reason. -

-

15.11.4.3 Check Accessibility of Type and Method

- -Let C be the class containing the method invocation, and let T be the class or interface -that contained the method being invoked, and m be the name of the method, -as determined at compile time (§15.11.3). -

-A Java Virtual Machine must insure, as part of linkage, that the method m still exists in the type T. If this is not true, then a NoSuchMethodError (which is a subclass of IncompatibleClassChangeError) occurs. If the invocation mode is interface, then the virtual machine must also check that the target reference type still implements the specified interface. If the target reference type does not still implement the interface, then an IncompatibleClassChangeError occurs.

- -The virtual machine must also insure, during linkage, that the type T and the method m are accessible. For the type T:

-

-For the method m: -

-If either T or m is not accessible, then an IllegalAccessError occurs (§12.3). -

-

15.11.4.4 Locate Method to Invoke

- -The strategy for method lookup depends on the invocation mode. -

-If the invocation mode is static, no target reference is needed and overriding is not allowed. Method m of class T is the one to be invoked.

- -Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is null, a NullPointerException is thrown at this point. Otherwise, the target reference is said to refer to a target object and will be used as the value of the keyword this in the invoked method. The other four possibilities for the invocation mode are then considered.

- -If the invocation mode is nonvirtual, overriding is not allowed. Method m of class T is the one to be invoked.

- -Otherwise, the invocation mode is interface, virtual, or super, and overriding may occur. A dynamic method lookup is used. The dynamic lookup process starts from a class S, determined as follows:

-

-The dynamic method lookup uses the following procedure to search class S, and -then the superclasses of class S, as necessary, for method m. -

    - -
  1. If class S contains a declaration for a method named m with the same descriptor (same number of parameters, the same parameter types, and the same return type) required by the method invocation as determined at compile time (§15.11.3), then this is the method to be invoked, and the procedure terminates. (We note that as part of the loading and linking process that the virtual machine checks that an overriding method is at least as accessible as the overridden method; an IncompatibleClassChangeError occurs if this is not the case.) - -
  2. Otherwise, if S is not T, this same lookup procedure is performed using the superclass of S; whatever it comes up with is the result of this lookup. -
- -This procedure will find a suitable method when it reaches class T, because otherwise -an IllegalAccessError would have been thrown by the checks of the previous -section §15.11.4.3. -

-We note that the dynamic lookup process, while described here explicitly, will often be implemented implicitly, for example as a side-effect of the construction and use of per-class method dispatch tables, or the construction of other per-class structures used for efficient dispatch.

- -

15.11.4.5 Create Frame, Synchronize, Transfer Control

- -A method m in some class S has been identified as the one to be invoked. -

-Now a new activation frame is created, containing the target reference (if any) and the argument values (if any), as well as enough space for the local variables and stack for the method to be invoked and any other bookkeeping information that may be required by the implementation (stack pointer, program counter, reference to previous activation frame, and the like). If there is not sufficient memory available to create such an activation frame, an OutOfMemoryError is thrown.

- -The newly created activation frame becomes the current activation frame. The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method, and to make the target reference available as this, if there is a target reference.

- -If the method m is a native method but the necessary native, implementation-dependent binary code has not been loaded (§20.16.14, §20.16.13) or otherwise cannot be dynamically linked, then an UnsatisfiedLinkError is thrown.

- -If the method m is not synchronized, control is transferred to the body of the method m to be invoked.

- -If the method m is synchronized, then an object must be locked before the transfer of control. No further progress can be made until the current thread can obtain the lock. If there is a target reference, then the target must be locked; otherwise the Class object for class S, the class of the method m, must be locked. Control is then transferred to the body of the method m to be invoked. The object is automatically unlocked when execution of the body of the method has completed, whether normally or abruptly. The locking and unlocking behavior is exactly as if the body of the method were embedded in a synchronized statement (§14.17).

- -

15.11.4.6 Implementation Note: Combining Frames

- -In order to allow certain kinds of code optimization, implementations are permitted -some freedom to combine activation frames. Suppose that a method invocation -within class C is to invoke a method m within class S. Then the current activation -frame may be used to provide space for S instead of creating a new activation -frame only if one of the following conditions is true: -

-

15.11.4.7 Example: Target Reference and Static Methods

- -When a target reference is computed and then discarded because the invocation -mode is static, the reference is not examined to see whether it is null: -


-class Test {
-	static void mountain() {
- System.out.println("Monadnock");
- } - - static Test favorite(){ - System.out.print("Mount "); - return null; - } - - public static void main(String[] args) { - favorite().mountain(); - } -} -
-which prints: -

Mount Monadnock
-
-Here favorite returns null, yet no NullPointerException is thrown. -

-

15.11.4.8 Example: Evaluation Order

- -As part of an instance method invocation (§15.11), there is an expression that -denotes the object to be invoked. This expression appears to be fully evaluated -before any part of any argument expression to the method invocation is evaluated. -

-So, for example, in:

-


-class Test {
-	public static void main(String[] args) {
-		String s = "one";
-		if (s.startsWith(s = "two"))
-			System.out.println("oops");
-	}
-}
-
-the occurrence of s before ".startsWith" is evaluated first, before the argument -expression s="two". Therefore, a reference to the string "one" is remembered as -the target reference before the local variable s is changed to refer to the string -"two". As a result, the startsWith method (§20.12.20) is invoked for target -object "one" with argument "two", so the result of the invocation is false, as the -string "one" does not start with "two". It follows that the test program does not -print "oops". -

-

15.11.4.9 Example: Overriding

- -In the example: -


-class Point {
-
-	final int EDGE = 20;
-	int x, y;
-
-	void move(int dx, int dy) {
-		x += dx; y += dy;
-		if (Math.abs(x) >= EDGE || Math.abs(y) >= EDGE)
-			clear();
-	}
-
-	void clear() {
-		System.out.println("\tPoint clear");
-		x = 0; y = 0;
-	}
-}
-
-class ColoredPoint extends Point {
-	int color;
-

-	void clear() {
-		System.out.println("\tColoredPoint clear");
-		super.clear();
-		color = 0;
-	}
-}
-
-the subclass ColoredPoint extends the clear abstraction defined by its superclass -Point. It does so by overriding the clear method with its own method, -which invokes the clear method of its superclass, using the form super.clear. -

-This method is then invoked whenever the target object for an invocation of clear is a ColoredPoint. Even the method move in Point invokes the clear method of class ColoredPoint when the class of this is ColoredPoint, as shown by the output of this test program:

-


-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		System.out.println("p.move(20,20):");
-		p.move(20, 20);
-		ColoredPoint cp = new ColoredPoint();
-		System.out.println("cp.move(20,20):");
-		cp.move(20, 20);
-		p = new ColoredPoint();
-		System.out.println("p.move(20,20), p colored:");
-		p.move(20, 20);
-	}
-}
-
-which is: -


-p.move(20,20):
-	Point clear
-cp.move(20,20):
-	ColoredPoint clear
-	Point clear
-p.move(20,20), p colored:
-	ColoredPoint clear
-	Point clear
-
-Overriding is sometimes called "late-bound self-reference"; in this example it means that the reference to clear in the body of Point.move (which is really syntactic shorthand for this.clear) invokes a method chosen "late" (at run time, based on the run-time class of the object referenced by this) rather than a method chosen "early" (at compile time, based only on the type of this). This provides the Java programmer a powerful way of extending abstractions and is a key idea in object-oriented programming.

- -

15.11.4.10 Example: Method Invocation using super

- -An overridden instance method of a superclass may be accessed by using the keyword -super to access the members of the immediate superclass, bypassing any -overriding declaration in the class that contains the method invocation. -

-When accessing an instance variable, super means the same as a cast of this (§15.10.2), but this equivalence does not hold true for method invocation. This is demonstrated by the example:

-


-class T1 {
-	String s() { return "1"; }
-}
-
-class T2 extends T1 {
-	String s() { return "2"; }
-}
-
-class T3 extends T2 {
-	String s() { return "3"; }
-
-	void test() {
-		System.out.println("s()=\t\t"+s());
-		System.out.println("super.s()=\t"+super.s());
-		System.out.print("((T2)this).s()=\t");
-			System.out.println(((T2)this).s());
-		System.out.print("((T1)this).s()=\t");
-			System.out.println(((T1)this).s());
-	}
-}
-
-class Test {
-	public static void main(String[] args) {
-		T3 t3 = new T3();
-		t3.test();
-	}
-}
-
-which produces the output: -


-s()=					3
-super.s()=					2
-((T2)this).s()=					3
-((T1)this).s()=					3
-
-The casts to types T1 and T2 do not change the method that is invoked, because -the instance method to be invoked is chosen according to the run-time class of the -object referred to be this. A cast does not change the class of an object; it only -checks that the class is compatible with the specified type. -

-

15.12 Array Access Expressions

- -An array access expression refers to a variable that is a component of an array. -

-An array access expression contains two subexpressions, the array reference expression (before the left bracket) and the index expression (within the brackets). Note that the array reference expression may be a name or any primary expression that is not an array creation expression (§15.9).

- -The type of the array reference expression must be an array type (call it T[], an array whose components are of type T) or a compile-time error results. Then the type of the array access expression is T.

- -The index expression undergoes unary numeric promotion (§5.6.1); the promoted type must be int.

- -The result of an array reference is a variable of type T, namely the variable within the array selected by the value of the index expression. This resulting variable, which is a component of the array, is never considered final, even if the array reference was obtained from a final variable.

- -

15.12.1 Runtime Evaluation of Array Access

- -An array access expression is evaluated using the following procedure: -

-

15.12.2 Examples: Array Access Evaluation Order

- -In an array access, the expression to the left of the brackets appears to be fully -evaluated before any part of the expression within the brackets is evaluated. For -example, in the (admittedly monstrous) expression a[(a=b)[3]], the expression -a is fully evaluated before the expression (a=b)[3]; this means that the original -value of a is fetched and remembered while the expression (a=b)[3] is evaluated. -This array referenced by the original value of a is then subscripted by a value -that is element 3 of another array (possibly the same array) that was referenced by -b and is now also referenced by a. -

-Thus, the example:

-


-class Test {
-	public static void main(String[] args) {
-		int[] a = { 11, 12, 13, 14 };
-		int[] b = { 0, 1, 2, 3 };
-		System.out.println(a[(a=b)[3]]);
-	}
-}
-
-prints: -

14
-
-because the monstrous expression's value is equivalent to a[b[3]] or a[3] or 14. -

-If evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated. Thus, the example:

-


-class Test {
-	public static void main(String[] args) {
-		int index = 1;
-		try {
-			skedaddle()[index=2]++;
-		} catch (Exception e) {
-			System.out.println(e + ", index=" + index);
-		}
-	}
-	static int[] skedaddle() throws Exception {
-		throw new Exception("Ciao");
-	}
-}
-
-prints: -

java.lang.Exception: Ciao, index=1
-
-because the embedded assignment of 2 to index never occurs. -

-If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at run time, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally. Thus, the example:

-


-class Test {
-
-	public static void main(String[] args) {
-		int index = 1;
-		try {
-			nada()[index=2]++;
-		} catch (Exception e) {
-			System.out.println(e + ", index=" + index);
-		}
-	}
-	static int[] nada() { return null; }
-}
-
-prints: -

java.lang.NullPointerException, index=2
-
-because the embedded assignment of 2 to index occurs before the check for a null -pointer. As a related example, the program: -


-class Test {
-
-	public static void main(String[] args) {
-		int[] a = null;
-		try {
-			int i = a[vamoose()];
-			System.out.println(i);
-		} catch (Exception e) {
-			System.out.println(e);
-		}
-	}
-
-	static int vamoose() throws Exception {
-		throw new Exception("Twenty-three skidoo!");
-	}
-}
-
-always prints: -

java.lang.Exception: Twenty-three skidoo!
-
-A NullPointerException never occurs, because the index expression must be -completely evaluated before any part of the indexing operation occurs, and that -includes the check as to whether the value of the left-hand operand is null. -

-

15.13 Postfix Expressions

- -Postfix expressions include uses of the postfix ++ and -- operators. Also, as discussed -in §15.7, names are not considered to be primary expressions, but are handled -separately in the grammar to avoid certain ambiguities. They become -interchangeable only here, at the level of precedence of postfix expressions. -

-

15.13.1 Names

- -A name occurring in an expression may be, syntactically, an ExpressionName -(§6.5). The meaning of such an ExpressionName depends on its form: -

-

15.13.2 Postfix Increment Operator ++

- -A postfix expression followed by a ++ operator is a postfix increment expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

- -A variable that is declared final cannot be incremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix increment operator.

- -

15.13.3 Postfix Decrement Operator --

- -A postfix expression followed by a -- operator is a postfix decrement expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix decrement expression is the type of the variable. The result of the postfix decrement expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the postfix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable before the new value is stored.

- -A variable that is declared final cannot be decremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix decrement operator.

- -

15.14 Unary Operators

- -The unary operators include +, -, ++, --, ~, !, and cast operators. Expressions -with unary operators group right-to-left, so that -~x means the same as -(~x). -

-The following productions from §15.15 are repeated here for convenience: -

-This portion of the Java grammar contains some tricks to avoid two potential syntactic ambiguities.

- -The first potential ambiguity would arise in expressions such as (p)+q, which looks, to a C or C++ programmer, as though it could be either be a cast to type p of a unary + operating on q, or a binary addition of two quantities p and q. In C and C++, the parser handles this problem by performing a limited amount of semantic analysis as it parses, so that it knows whether p is the name of a type or the name of a variable.

- -Java takes a different approach. The result of the + operator must be numeric, and all type names involved in casts on numeric values are known keywords. Thus, if p is a keyword naming a primitive type, then (p)+q can make sense only as a cast of a unary expression. However, if p is not a keyword naming a primitive type, then (p)+q can make sense only as a binary arithmetic operation. Similar remarks apply to the - operator. The grammar shown above splits CastExpression into two cases to make this distinction. The nonterminal UnaryExpression includes all unary operator, but the nonterminal UnaryExpressionNotPlusMinus excludes uses of all unary operators that could also be binary operators, which in Java are + and -.

- -The second potential ambiguity is that the expression (p)++ could, to a C or C++ programmer, appear to be either a postfix increment of a parenthesized expression or the beginning of a cast, for example, in (p)++q. As before, parsers for C and C++ know whether p is the name of a type or the name of a variable. But a parser using only one-token lookahead and no semantic analysis during the parse would not be able to tell, when ++ is the lookahead token, whether (p) should be considered a Primary expression or left alone for later consideration as part of a CastExpression.

- -In Java, the result of the ++ operator must be numeric, and all type names involved in casts on numeric values are known keywords. Thus, if p is a keyword naming a primitive type, then (p)++ can make sense only as a cast of a prefix increment expression, and there had better be an operand such as q following the ++. However, if p is not a keyword naming a primitive type, then (p)++ can make sense only as a postfix increment of p. Similar remarks apply to the -- operator. The nonterminal UnaryExpressionNotPlusMinus therefore also excludes uses of the prefix operators ++ and --.

- -

15.14.1 Prefix Increment Operator ++

- -A unary expression preceded by a ++ operator is a prefix increment expression. -The result of the unary expression must be a variable of a numeric type, or a compile-time -error occurs. The type of the prefix increment expression is the type of -the variable. The result of the prefix increment expression is not a variable, but a -value. -

-At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.

- -A variable that is declared final cannot be incremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix increment operator.

- -

15.14.2 Prefix Decrement Operator --

- -A unary expression preceded by a -- operator is a prefix decrement expression. -The result of the unary expression must be a variable of a numeric type, or a compile-time -error occurs. The type of the prefix decrement expression is the type of -the variable. The result of the prefix decrement expression is not a variable, but a -value. -

-At run time, if evaluation of the operand expression completes abruptly, then the prefix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.

- -A variable that is declared final cannot be decremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix decrement operator.

- -

15.14.3 Unary Plus Operator +

- -The type of the operand expression of the unary + operator must be a primitive -numeric type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) -is performed on the operand. The type of the unary plus expression is the promoted -type of the operand. The result of the unary plus expression is not a variable, -but a value, even if the result of the operand expression is a variable. -

-At run time, the value of the unary plus expression is the promoted value of the operand.

- -

15.14.4 Unary Minus Operator -

- -The type of the operand expression of the unary - operator must be a primitive -numeric type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) -is performed on the operand. The type of the unary minus expression is the promoted -type of the operand. -

-At run time, the value of the unary plus expression is the arithmetic negation of the promoted value of the operand.

- -For integer values, negation is the same as subtraction from zero. Java uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.

- -For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x equals +0.0, but -x equals -0.0. Unary minus merely inverts the sign of a floating-point number. Special cases of interest:

-

-

15.14.5 Bitwise Complement Operator ~

- -The type of the operand expression of the unary ~ operator must be a primitive -integral type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) is -performed on the operand. The type of the unary bitwise complement expression -is the promoted type of the operand. -

-At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand; note that, in all cases, ~x equals (-x)-1.

- -

15.14.6 Logical Complement Operator !

- -The type of the operand expression of the unary ! operator must be boolean, or a -compile-time error occurs. The type of the unary logical complement expression -is boolean. -

-At run time, the value of the unary logical complement expression is true if the operand value is false and false if the operand value is true.

- -

15.15 Cast Expressions

- -A cast expression converts, at run time, a value of one numeric type to a similar -value of another numeric type; or confirms, at compile time, that the type of an -expression is boolean; or checks, at run time, that a reference value refers to an -object whose class is compatible with a specified reference type. -

-See §15.14 for a discussion of the distinction between UnaryExpression and UnaryExpressionNotPlusMinus.

- -The type of a cast expression is the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the cast operator.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.

- -At run time, the operand value is converted by casting conversion (§5.4) to the type specified by the cast operator.

- -Not all casts are permitted by the Java language. Some casts result in an error at compile time. For example, a primitive value may not be cast to a reference type. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time. A ClassCastException is thrown if a cast is found at run time to be impermissible.

- -

15.16 Multiplicative Operators

- -The operators *, /, and % are called the multiplicative operators. They have the -same precedence and are syntactically left-associative (they group left-to-right). -

-The type of each of the operands of a multiplicative operator must be a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). The type of a multiplicative expression is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

- -

15.16.1 Multiplication Operator *

- -The binary * operator performs multiplication, producing the product of its operands. -Multiplication is a commutative operation if the operand expressions have -no side effects. While integer multiplication is associative when the operands are -all of the same type, floating-point multiplication is not associative. -

-If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

- -The result of a floating-point multiplication is governed by the rules of IEEE 754 arithmetic:

-

-Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a multiplication operator * never throws a run-time exception.

- -

15.16.2 Division Operator /

- -The binary / operator performs division, producing the quotient of its operands. -The left-hand operand is the dividend and the right-hand operand is the divisor. -

-Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying ; moreover, q is positive when and n and d have the same sign, but q is negative when and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

- -The result of a floating-point division is determined by the specification of IEEE arithmetic:

-

-Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator / never throws a run-time exception.

- -

15.16.3 Remainder Operator %

- -The binary % operator is said to yield the remainder of its operands from an -implied division; the left-hand operand is the dividend and the right-hand operand -is the divisor. -

-In C and C++, the remainder operator accepts only integral operands, but in Java, it also accepts floating-point operands.

- -The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown.

- -Examples:

-


-5%3 produces 2							(note that 5/3 produces 1)
-5%(-3) produces 2							(note that 5/(-3) produces -1)
-(-5)%3 produces -2							(note that (-5)/3 produces -1)
-(-5)%(-3) produces -2							(note that (-5)/(-3) produces 1)
-
-The result of a floating-point remainder operation as computed by the % operator is not the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is not analogous to that of the usual integer remainder operator. Instead, the Java language defines % on floating-point operations to behave in a manner analogous to that of the Java integer remainder operator; this may be compared with the C library function fmod. The IEEE 754 remainder operation may be computed by the Java library routine Math.IEEEremainder (§20.11.14).

- -The result of a Java floating-point remainder operation is determined by the rules of IEEE arithmetic:

-

-Evaluation of a floating-point remainder operator % never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur.

- -Examples:

-


-5.0%3.0 produces 2.0
-5.0%(-3.0) produces 2.0
-(-5.0)%3.0 produces -2.0
-(-5.0)%(-3.0) produces -2.0
-
-

15.17 Additive Operators

- -The operators + and - are called the additive operators. They have the same precedence -and are syntactically left-associative (they group left-to-right). -

-If the type of either operand of a + operator is String, then the operation is string concatenation.

- -Otherwise, the type of each of the operands of the + operator must be a primitive numeric type, or a compile-time error occurs.

- -In every case, the type of each of the operands of the binary - operator must be a primitive numeric type, or a compile-time error occurs.

- -

15.17.1 String Concatenation Operator +

- -If only one operand expression is of type String, then string conversion is performed -on the other operand to produce a string at run time. The result is a reference -to a newly created String object that is the concatenation of the two -operand strings. The characters of the left-hand operand precede the characters of -the right-hand operand in the newly created string. -

-

15.17.1.1 String Conversion

- -Any type may be converted to type String by string conversion. -

-A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:

-

-This reference value is then converted to type String by string conversion. -

-Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead. The toString method (§20.1.2) is defined by the primordial class Object (§20.1); many classes override it, notably Boolean, Character, Integer, Long, Float, Double, and String.

- -

15.17.1.2 Optimization of String Concatenation

- -An implementation may choose to perform conversion and concatenation in one -step to avoid creating and then discarding an intermediate String object. To -increase the performance of repeated string concatenation, a Java compiler may -use the StringBuffer class (§20.13) or a similar technique to reduce the number -of intermediate String objects that are created by evaluation of an expression. -

-For primitive objects, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

- -

15.17.1.3 Examples of String Concatenation

- -The example expression: -

"The square root of 2 is " + Math.sqrt(2)
-
-produces the result: -

"The square root of 2 is 1.4142135623730952"
-
-The + operator is syntactically left-associative, no matter whether it is later determined by type analysis to represent string concatenation or addition. In some cases care is required to get the desired result. For example, the expression:

-

a + b + c
-
-is always regarded as meaning: -

(a + b) + c
-
-Therefore the result of the expression: -

1 + 2 + " fiddlers"
-
-is: -

"3 fiddlers"
-
-but the result of: -

"fiddlers " + 1 + 2
-
-is: -

"fiddlers 12"
-
-In this jocular little example:

-


-class Bottles {
-
-	static void printSong(Object stuff, int n) {
-		String plural = "s";
-		loop: while (true) {
-			System.out.println(n + " bottle" + plural
-				+ " of " + stuff + " on the wall,");
-			System.out.println(n + " bottle" + plural
-				+ " of " + stuff + ";");
-			System.out.println("You take one down "
-				+ "and pass it around:");
-			--n;
-			plural = (n == 1) ? "" : "s";
-			if (n == 0)
-				break loop;
-			System.out.println(n + " bottle" + plural
-				+ " of " + stuff + " on the wall!");
-			System.out.println();
-		}
-		System.out.println("No bottles of " +
-								stuff + " on the wall!");
-	}
-
} -
-the method printSong will print a version of a children's song. Popular values -for stuff include "pop" and "beer"; the most popular value for n is 100. Here is -the output that results from Bottles.printSong("slime", 3): -


-3 bottles of slime on the wall,
-3 bottles of slime;
-You take one down and pass it around:
-2 bottles of slime on the wall!
-
-2 bottles of slime on the wall,
-2 bottles of slime;
-You take one down and pass it around:
-1 bottle of slime on the wall!
-
-1 bottle of slime on the wall,
-1 bottle of slime;
-You take one down and pass it around:
-No bottles of slime on the wall!
-
-In the code, note the careful conditional generation of the singular "bottle" when appropriate rather than the plural "bottles"; note also how the string concatenation operator was used to break the long constant string:

-

"You take one down and pass it around:"
-
-into two pieces to avoid an inconveniently long line in the source code. -

-

15.17.2 Additive Operators (+ and -) for Numeric Types

- -The binary + operator performs addition when applied to two operands of numeric -type, producing the sum of the operands. The binary - operator performs subtraction, -producing the difference of two numeric operands. -

-Binary numeric promotion is performed on the operands (§5.6.2). The type of an additive expression on numeric operands is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

- -Addition is a commutative operation if the operand expressions have no side effects. Integer addition is associative when the operands are all of the same type, but floating-point addition is not associative.

- -If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

- -The result of a floating-point addition is determined using the following rules of IEEE arithmetic:

-

-The binary - operator performs subtraction when applied to two operands of numeric type producing the difference of its operands; the left-hand operand is the minuend and the right-hand operand is the subtrahend. For both integer and floating-point subtraction, it is always the case that a-b produces the same result as a+(-b). Note that, for integer values, subtraction from zero is the same as negation. However, for floating-point operands, subtraction from zero is not the same as negation, because if x is +0.0, then 0.0-x equals +0.0, but -x equals -0.0.

- -Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a run-time exception.

- -

15.18 Shift Operators

- -The shift operators include left shift <<, signed right shift >>, and unsigned right -shift >>>; they are syntactically left-associative (they group left-to-right). The left- -hand operand of a shift operator is the value to be shifted; the right-hand operand -specifies the shift distance. -

-The type of each of the operands of a shift operator must be a primitive integral type, or a compile-time error occurs. Binary numeric promotion (§5.6.2) is not performed on the operands; rather, unary numeric promotion (§5.6.1) is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.

- -If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.21.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

- -If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.21.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

- -At run time, shift operations are performed on the two's complement integer representation of the value of the left operand.

- -The value of n<<s is n left-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s.

- -The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is . For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.

- -The value of n>>>s is n right-shifted s bit positions with zero-extension. If n is positive, then the result is the same as that of n>>s; if n is negative, the result is equal to that of the expression (n>>s)+(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)+(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a long value.)

- -

15.19 Relational Operators

- -The relational operators are syntactically left-associative (they group left-to- -right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is -always a compile-time error, because the type of a<b is always boolean and < is -not an operator on boolean values. -

-The type of a relational expression is always boolean. -

-

15.19.1 Numerical Comparison Operators <, <=, >, and >=

- -The type of each of the operands of a numerical comparison operator must be a -primitive numeric type, or a compile-time error occurs. Binary numeric promotion -is performed on the operands (§5.6.2). If the promoted type of the operands is int -or long, then signed integer comparison is performed; if this promoted type is -float or double, then floating-point comparison is performed. -

-The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:

-

-Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

-

-

15.19.2 Type Comparison Operator instanceof

- -The type of a RelationalExpression operand of the instanceof operator must be -a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType - mentioned after the instanceof operator must denote a reference -type; otherwise, a compile-time error occurs. -

-At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.15) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

- -If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

- -Consider the example program:

-

class Point { int x, y; }
-class Element { int atomicNumber; }
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		Element e = new Element();
-		if (e instanceof Point) {											// compile-time error
-			System.out.println("I get your point!");
-			p = (Point)e;										// compile-time error
-		}
-	}
-}
-
-This example results in two compile-time errors. The cast (Point)e is incorrect -because no instance of Element or any of its possible subclasses (none are shown -here) could possibly be an instance of any subclass of Point. The instanceof -expression is incorrect for exactly the same reason. If, on the other hand, the class -Point were a subclass of Element (an admittedly strange notion in this example): -

class Point extends Element { int x, y; }
-
-then the cast would be possible, though it would require a run-time check, and the -instanceof expression would then be sensible and valid. The cast (Point)e -would never raise an exception because it would not be executed if the value of e -could not correctly be cast to type Point. -

-

15.20 Equality Operators

- -The equality operators are syntactically left-associative (they group left-to-right), -but this fact is essentially never useful; for example, a==b==c parses as -(a==b)==c. The result type of a==b is always boolean, and c must therefore be -of type boolean or a compile-time error occurs. Thus, a==b==c does not test to -see whether a, b, and c are all equal. -

-The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.

- -The equality operators may be used to compare two operands of numeric type, or two operands of type boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.

- -In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.

- -

15.20.1 Numerical Equality Operators == and !=

- -If the operands of an equality operator are both of primitive numeric type, binary -numeric promotion is performed on the operands (§5.6.2). If the promoted type of -the operands is int or long, then an integer equality test is performed; if the promoted -type is float or double, then a floating-point equality test is performed. -

-Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

-

-Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

-

-

15.20.2 Boolean Equality Operators == and !=

- -If the operands of an equality operator are both of type boolean, then the operation -is boolean equality. The boolean equality operators are associative. -

-The result of == is true if the operands are both true or both false; otherwise, the result is false.

- -The result of != is false if the operands are both true or both false; otherwise, the result is true. Thus != behaves the same as ^ (§15.21.2) when applied to boolean operands.

- -

15.20.3 Reference Equality Operators == and !=

- -If the operands of an equality operator are both of either reference type or the null -type, then the operation is object equality. -

-A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.4). The run-time values of the two operands would necessarily be unequal.

- -At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

- -The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.

- -While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of two strings s and t can be tested for equality by the method invocation s.equals(t) (§20.12.9). See also §3.10.5 and §20.12.47.

- -

15.21 Bitwise and Logical Operators

- -The bitwise operators and logical operators include the AND operator &, exclusive -OR operator ^, and inclusive OR operator |. These operators have different -precedence, with & having the highest precedence and | the lowest precedence. -Each of these operators is syntactically left-associative (each groups left-to-right). -Each operator is commutative if the operand expressions have no side effects. -Each operator is associative. -

-The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type boolean. All other cases result in a compile-time error.

- -

15.21.1 Integer Bitwise Operators &, ^, and |

- -When both operands of an operator &, ^, or | are of primitive integral type, binary -numeric promotion is first performed on the operands (§5.6.2). The type of the bitwise -operator expression is the promoted type of the operands. -

-For &, the result value is the bitwise AND of the operand values.

- -For ^, the result value is the bitwise exclusive OR of the operand values.

- -For |, the result value is the bitwise inclusive OR of the operand values.

- -For example, the result of the expression 0xff00 & 0xf0f0 is 0xf000. The result of 0xff00 ^ 0xf0f0 is 0x0ff0.The result of 0xff00 | 0xf0f0 is 0xfff0.

- -

15.21.2 Boolean Logical Operators &, ^, and |

- -When both operands of a &, ^, or | operator are of type boolean, then the type of -the bitwise operator expression is boolean. -

-For &, the result value is true if both operand values are true; otherwise, the result is false.

- -For ^, the result value is true if the operand values are different; otherwise, the result is false.

- -For |, the result value is false if both operand values are false; otherwise, the result is true.

- -

15.22 Conditional-And Operator &&

- -The && operator is like & (§15.21.2), but evaluates its right-hand operand only if -the value of its left-hand operand is true. It is syntactically left-associative (it -groups left-to-right). It is fully associative with respect to both side effects and -result value; that is, for any expressions a, b, and c, evaluation of the expression -((a)&&(b))&&(c) produces the same result, with the same side effects occurring -in the same order, as evaluation of the expression (a)&&((b)&&(c)). -

-Each operand of && must be of type boolean, or a compile-time error occurs. The type of a conditional-and expression is always boolean.

- -At run time, the left-hand operand expression is evaluated first; if its value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

- -

15.23 Conditional-Or Operator ||

- -The || operator is like | (§15.21.2), but evaluates its right-hand operand only if -the value of its left-hand operand is false. It is syntactically left-associative (it -groups left-to-right). It is fully associative with respect to both side effects and -result value; that is, for any expressions a, b, and c, evaluation of the expression -((a)||(b))||(c) produces the same result, with the same side effects occurring -in the same order, as evaluation of the expression (a)||((b)||(c)). -

-Each operand of || must be of type boolean, or a compile-time error occurs. The type of a conditional-or expression is always boolean.

- -At run time, the left-hand operand expression is evaluated first; if its value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression. Thus, || computes the same result as | on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

- -

15.24 Conditional Operator ? :

- -The conditional operator ? : uses the boolean value of one expression to decide -which of two other expressions should be evaluated. -

-The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

-

-The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.

- -The first expression must be of type boolean, or a compile-time error occurs.

- -The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type boolean, or second and third operands that are each of either reference type or the null type. All other cases result in a compile-time error.

- -Note that it is not permitted for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear (§14.7).

- -The type of a conditional expression is determined as follows:

-

-At run time, the first operand expression of the conditional expression is evaluated first; its boolean value is then used to choose either the second or the third operand expression:

-

-The chosen operand expression is then evaluated and the resulting value is converted -to the type of the conditional expression as determined by the rules stated -above. The operand expression not chosen is not evaluated for that particular evaluation -of the conditional expression. -

-

15.25 Assignment Operators

- -There are 12 assignment operators; all are syntactically right-associative (they -group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to -b and then assigns the value of b to a. -

-The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. This operand may be a named variable, such as a local variable or a field of the current object or class, or it may be a computed variable, as can result from a field access (§15.10) or an array access (§15.12). The type of the assignment expression is the type of the variable.

- -At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

- -A variable that is declared final cannot be assigned to, because when an access of a final variable is used as an expression, the result is a value, not a variable, and so it cannot be used as the operand of an assignment operator.

- -

15.25.1 Simple Assignment Operator =

- -A compile-time error occurs if the type of the right-hand operand cannot be converted -to the type of the variable by assignment conversion (§5.2). -

-At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then three steps are required:

-

-If the left-hand operand expression is an array access expression (§15.12), then -many steps are required: -

-The rules for assignment to an array component are illustrated by the following -example program: -


class ArrayReferenceThrow extends RuntimeException { } -

class IndexThrow extends RuntimeException { } -

class RightHandSideThrow extends RuntimeException { } -

-class IllustrateSimpleArrayAssignment {
-
static Object[] objects = { new Object(), new Object() }; -

static Thread[] threads = { new Thread(), new Thread() }; -
- static Object[] arrayThrow() { - throw new ArrayReferenceThrow(); - } -

static int indexThrow() { throw new IndexThrow(); } -
- static Thread rightThrow() { - throw new RightHandSideThrow(); - } -
- static String name(Object q) { - String sq = q.getClass().getName(); - int k = sq.lastIndexOf('.'); - return (k < 0) ? sq : sq.substring(k+1); - } -
- static void testFour(Object[] x, int j, Object y) { - String sx = x == null ? "null" : name(x[0]) + "s"; - String sy = name(y); - System.out.println(); - try { - System.out.print(sx + "[throw]=throw => "); - x[indexThrow()] = rightThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sx + "[throw]=" + sy + " => "); - x[indexThrow()] = y; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sx + "[" + j + "]=throw => "); - x[j] = rightThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sx + "[" + j + "]=" + sy + " => "); - x[j] = y; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - } -
- public static void main(String[] args) { - try { - System.out.print("throw[throw]=throw => "); - arrayThrow()[indexThrow()] = rightThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[throw]=Thread => "); - arrayThrow()[indexThrow()] = new Thread(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[1]=throw => "); - arrayThrow()[1] = rightThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[1]=Thread => "); - arrayThrow()[1] = new Thread(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - - testFour(null, 1, new StringBuffer()); - testFour(null, 1, new StringBuffer()); - testFour(null, 9, new Thread()); - testFour(null, 9, new Thread()); - testFour(objects, 1, new StringBuffer()); - testFour(objects, 1, new Thread()); - testFour(objects, 9, new StringBuffer()); - testFour(objects, 9, new Thread()); - testFour(threads, 1, new StringBuffer()); - testFour(threads, 1, new Thread()); - testFour(threads, 9, new StringBuffer()); - testFour(threads, 9, new Thread()); - } -
} -
-This program prints: -


-throw[throw]=throw => ArrayReferenceThrow
-throw[throw]=Thread => ArrayReferenceThrow
-throw[1]=throw => ArrayReferenceThrow
-throw[1]=Thread => ArrayReferenceThrow
-
-null[throw]=throw => IndexThrow -null[throw]=StringBuffer => IndexThrow -null[1]=throw => RightHandSideThrow -null[1]=StringBuffer => NullPointerException -
-null[throw]=throw => IndexThrow -null[throw]=StringBuffer => IndexThrow -null[1]=throw => RightHandSideThrow -null[1]=StringBuffer => NullPointerException -
-null[throw]=throw => IndexThrow -null[throw]=Thread => IndexThrow -null[9]=throw => RightHandSideThrow -null[9]=Thread => NullPointerException -
-null[throw]=throw => IndexThrow -null[throw]=Thread => IndexThrow -null[9]=throw => RightHandSideThrow -null[9]=Thread => NullPointerException -
-Objects[throw]=throw => IndexThrow -Objects[throw]=StringBuffer => IndexThrow -Objects[1]=throw => RightHandSideThrow -Objects[1]=StringBuffer => Okay! -
-Objects[throw]=throw => IndexThrow -Objects[throw]=Thread => IndexThrow -Objects[1]=throw => RightHandSideThrow -Objects[1]=Thread => Okay! -
-Objects[throw]=throw => IndexThrow -Objects[throw]=StringBuffer => IndexThrow -Objects[9]=throw => RightHandSideThrow -Objects[9]=StringBuffer => IndexOutOfBoundsException -
-Objects[throw]=throw => IndexThrow -Objects[throw]=Thread => IndexThrow -Objects[9]=throw => RightHandSideThrow -Objects[9]=Thread => IndexOutOfBoundsException -
-Threads[throw]=throw => IndexThrow -Threads[throw]=StringBuffer => IndexThrow -Threads[1]=throw => RightHandSideThrow -Threads[1]=StringBuffer => ArrayStoreException -
-Threads[throw]=throw => IndexThrow -Threads[throw]=Thread => IndexThrow -Threads[1]=throw => RightHandSideThrow -Threads[1]=Thread => Okay! -
-Threads[throw]=throw => IndexThrow -Threads[throw]=StringBuffer => IndexThrow -Threads[9]=throw => RightHandSideThrow -Threads[9]=StringBuffer => IndexOutOfBoundsException -
-Threads[throw]=throw => IndexThrow -Threads[throw]=Thread => IndexThrow -Threads[9]=throw => RightHandSideThrow -Threads[9]=Thread => IndexOutOfBoundsException -
-The most interesting case of the lot is the one thirteenth from the end: -

Threads[1]=StringBuffer => ArrayStoreException
-
-which indicates that the attempt to store a reference to a StringBuffer into an -array whose components are of type Thread throws an ArrayStoreException. -The code is type-correct at compile time: the assignment has a left-hand side of -type Object[] and a right-hand side of type Object. At run time, the first actual -argument to method testFour is a reference to an instance of "array of Thread" -and the third actual argument is a reference to an instance of class StringBuffer. -

-

15.25.2 Compound Assignment Operators

- -All compound assignment operators require both operands to be of primitive type, -except for +=, which allows the right-hand operand to be of any type if the left- -hand operand is of type String. -

-A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. Note that the implied cast to type T may be either an identity conversion (§5.1.1) or a narrowing primitive conversion (§5.1.3). For example, the following code is correct:

-


-short x = 3;
-x += 4.6;
-
-and results in x having the value 7 because it is equivalent to: -


-short x = 3;
-x = (short)(x + 4.6);
-
-At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:

-

-If the left-hand operand expression is an array access expression (§15.12), then -many steps are required: -

-The rules for compound assignment to an array component are illustrated by the -following example program: -


class ArrayReferenceThrow extends RuntimeException { } -

class IndexThrow extends RuntimeException { } -

class RightHandSideThrow extends RuntimeException { } -
class IllustrateCompoundArrayAssignment { -
static String[] strings = { "Simon", "Garfunkel" }; -

static double[] doubles = { Math.E, Math.PI }; -

-	static String[] stringsThrow() {
-		throw new ArrayReferenceThrow();
-	}
-
- static double[] doublesThrow() { - throw new ArrayReferenceThrow(); - } -

static int indexThrow() { throw new IndexThrow(); } -
- static String stringThrow() { - throw new RightHandSideThrow(); - } -
- static double doubleThrow() { - throw new RightHandSideThrow(); - } -
- static String name(Object q) { - String sq = q.getClass().getName(); - int k = sq.lastIndexOf('.'); - return (k < 0) ? sq : sq.substring(k+1); - } -
- static void testEight(String[] x, double[] z, int j) { - String sx = (x == null) ? "null" : "Strings"; - String sz = (z == null) ? "null" : "doubles"; - System.out.println(); - try { - System.out.print(sx + "[throw]+=throw => "); - x[indexThrow()] += stringThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sz + "[throw]+=throw => "); - z[indexThrow()] += doubleThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - - try { - System.out.print(sx + "[throw]+=\"heh\" => "); - x[indexThrow()] += "heh"; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sz + "[throw]+=12345 => "); - z[indexThrow()] += 12345; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sx + "[" + j + "]+=throw => "); - x[j] += stringThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sz + "[" + j + "]+=throw => "); - z[j] += doubleThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sx + "[" + j + "]+=\"heh\" => "); - x[j] += "heh"; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print(sz + "[" + j + "]+=12345 => "); - z[j] += 12345; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - } -
- public static void main(String[] args) { - try { - System.out.print("throw[throw]+=throw => "); - stringsThrow()[indexThrow()] += stringThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[throw]+=throw => "); - doublesThrow()[indexThrow()] += doubleThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[throw]+=\"heh\" => "); - stringsThrow()[indexThrow()] += "heh"; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - - try { - System.out.print("throw[throw]+=12345 => "); - doublesThrow()[indexThrow()] += 12345; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[1]+=throw => "); - stringsThrow()[1] += stringThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[1]+=throw => "); - doublesThrow()[1] += doubleThrow(); - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[1]+=\"heh\" => "); - stringsThrow()[1] += "heh"; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - try { - System.out.print("throw[1]+=12345 => "); - doublesThrow()[1] += 12345; - System.out.println("Okay!"); - } catch (Throwable e) { System.out.println(name(e)); } - - testEight(null, null, 1); - testEight(null, null, 9); - testEight(strings, doubles, 1); - testEight(strings, doubles, 9); - } -
} -
-This program prints: -


-throw[throw]+=throw => ArrayReferenceThrow
-throw[throw]+=throw => ArrayReferenceThrow
-throw[throw]+="heh" => ArrayReferenceThrow
-throw[throw]+=12345 => ArrayReferenceThrow
-throw[1]+=throw => ArrayReferenceThrow
-throw[1]+=throw => ArrayReferenceThrow
-throw[1]+="heh" => ArrayReferenceThrow
-throw[1]+=12345 => ArrayReferenceThrow
-
-null[throw]+=throw => IndexThrow -null[throw]+=throw => IndexThrow -null[throw]+="heh" => IndexThrow -null[throw]+=12345 => IndexThrow -null[1]+=throw => NullPointerException -null[1]+=throw => NullPointerException -null[1]+="heh" => NullPointerException -null[1]+=12345 => NullPointerException -
-null[throw]+=throw => IndexThrow -null[throw]+=throw => IndexThrow -null[throw]+="heh" => IndexThrow -null[throw]+=12345 => IndexThrow -null[9]+=throw => NullPointerException -null[9]+=throw => NullPointerException -null[9]+="heh" => NullPointerException -null[9]+=12345 => NullPointerException -
-Strings[throw]+=throw => IndexThrow -doubles[throw]+=throw => IndexThrow -Strings[throw]+="heh" => IndexThrow -doubles[throw]+=12345 => IndexThrow -Strings[1]+=throw => RightHandSideThrow -doubles[1]+=throw => RightHandSideThrow -Strings[1]+="heh" => Okay! -doubles[1]+=12345 => Okay! -
-Strings[throw]+=throw => IndexThrow -doubles[throw]+=throw => IndexThrow -Strings[throw]+="heh" => IndexThrow -doubles[throw]+=12345 => IndexThrow -Strings[9]+=throw => IndexOutOfBoundsException -doubles[9]+=throw => IndexOutOfBoundsException -Strings[9]+="heh" => IndexOutOfBoundsException -doubles[9]+=12345 => IndexOutOfBoundsException -
-The most interesting cases of the lot are tenth and eleventh from the end: -


-Strings[1]+=throw => RightHandSideThrow
-doubles[1]+=throw => RightHandSideThrow
-
-They are the cases where a right-hand side that throws an exception actually gets -to throw the exception; moreover, they are the only such cases in the lot. This -demonstrates that the evaluation of the right-hand operand indeed occurs after the -checks for a null array reference value and an out-of-bounds index value. -

-The following program illustrates the fact that the value of the left-hand side of a compound assignment is saved before the right-hand side is evaluated:

-


-class Test {
-	public static void main(String[] args) {
-		int k = 1;
-		int[] a = { 1 };
-		k += (k = 4) * (k + 2);
-		a[0] += (a[0] = 4) * (a[0] + 2);
-		System.out.println("k==" + k + " and a[0]==" + a[0]);
-	}
-}
-
-This program prints: -

k==25 and a[0]==25
-
-The value 1 of k is saved by the compound assignment operator += before its -right-hand operand (k = 4) * (k + 2) is evaluated. Evaluation of this right-hand -operand then assigns 4 to k, calculates the value 6 for k + 2, and then multiplies -4 by 6 to get 24. This is added to the saved value 1 to get 25, which is then stored -into k by the += operator. An identical analysis applies to the case that uses a[0]. -In short, the statements -


-k += (k = 4) * (k + 2);
-a[0] += (a[0] = 4) * (a[0] + 2);
-
-behave in exactly the same manner as the statements: -


-k = k + (k = 4) * (k + 2);
-a[0] = a[0] + (a[0] = 4) * (a[0] + 2);
-
-

15.26 Expression

- -An Expression is any assignment expression: -

-Unlike C and C++, the Java language has no comma operator. -

-

15.27 Constant Expression

- -A compile-time constant expression is an expression denoting a value of primitive type or a String that is composed using only the following:

-

-Compile-time constant expressions are used in case labels in switch statements -(§14.9) and have a special significance for assignment conversion (§5.2). -

-Examples of constant expressions:

-

true
-(short)(1*2*3*4*5*6)
-Integer.MAX_VALUE / 2
-2.0 * Math.PI
-"The integer " + Long.MAX_VALUE + " is mighty big."
-
- -
- - - - -
Contents | Prev | Next | IndexJava Language Specification
-First Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)
-Copyright © 1996 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- \ No newline at end of file diff --git a/topics/java/jls1/impl.html b/topics/java/jls1/impl.html new file mode 100644 index 00000000..24f97703 --- /dev/null +++ b/topics/java/jls1/impl.html @@ -0,0 +1,239 @@ + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +

+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/19.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/19.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + diff --git a/topics/java/jls1/read.html b/topics/java/jls1/read.html new file mode 100644 index 00000000..2da7763a --- /dev/null +++ b/topics/java/jls1/read.html @@ -0,0 +1,1912 @@ + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/4.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/4.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/6.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/6.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/7.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/7.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/8.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/8.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/9.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/9.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/10.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/10.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/14.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/14.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/first_edition/html/15.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/first_edition/html/15.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + diff --git a/topics/java/jls2/Makefile b/topics/java/jls2/Makefile index 61e8a36c..951d29c1 100644 --- a/topics/java/jls2/Makefile +++ b/topics/java/jls2/Makefile @@ -1,25 +1,25 @@ all: - make app - make doc + make impl + make read make test debug: - python ../../extraction/html2bgf/html2bgf.py app.html app2.bgf -v - python ../../extraction/html2bgf/getpre.py collect.kw doc.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html doc2.bgf -v + python ../../extraction/html2bgf/html2bgf.py impl.html impl2.bgf -v + python ../../extraction/html2bgf/getpre.py collect.kw read.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html read2.bgf -v -app: - @echo "Extracting app2" > /dev/stderr - python ../../extraction/html2bgf/html2bgf.py app.html app2.bgf +impl: + @echo "Extracting impl2" > /dev/stderr + python ../../extraction/html2bgf/html2bgf.py impl.html impl2.bgf -doc: - @echo "Extracting doc2" > /dev/stderr - python ../../extraction/html2bgf/getpre.py collect.kw doc.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html doc2.bgf +read: + @echo "Extracting read2" > /dev/stderr + python ../../extraction/html2bgf/getpre.py collect.kw read.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html read2.bgf test: - ../../../shared/tools/checkxml bgf app2.bgf - ../../../shared/tools/checkxml bgf doc2.bgf + ../../../shared/tools/checkxml bgf impl2.bgf + ../../../shared/tools/checkxml bgf read2.bgf clean: rm -f *.bgf parse.html diff --git a/topics/java/jls2/app.html b/topics/java/jls2/app.html deleted file mode 100644 index dc242dc9..00000000 --- a/topics/java/jls2/app.html +++ /dev/null @@ -1,399 +0,0 @@ - - - Syntax - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 18

- -

Syntax

-

- -This chapter presents a grammar for the Java programming language.

- -The grammar presented piecemeal in the preceding chapters is much better for exposition, but it is not ideally suited as a basis for a parser. The grammar presented in this chapter is the basis for the reference implementation.

- -The grammar below uses the following BNF-style conventions:

-

-

18.1 The Grammar of the Java Programming Language

- - -
- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - - diff --git a/topics/java/jls2/doc.html b/topics/java/jls2/doc.html deleted file mode 100644 index 8a484f8d..00000000 --- a/topics/java/jls2/doc.html +++ /dev/null @@ -1,9299 +0,0 @@ - - - Types, Values, and Variables - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 4

- -

Types, Values, and Variables

-

- -The Java programming language is a strongly typed language, which means that every variable and every expression has a type that is known at compile time. Types limit the values that a variable (§4.5) can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong typing helps detect errors at compile time.

- -The types of the Java programming language are divided into two categories: primitive types and reference types. The primitive types (§4.2) are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types (§4.3) are class types, interface types, and array types. There is also a special null type. An object (§4.3.1) is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object (§4.3.2). String literals are represented by String objects (§4.3.3).

- -Names of types are used (§4.4) in declarations, casts, class instance creation expressions, array creation expressions, class literals, and instanceof operator expressions.

- -A variable (§4.5) is a storage location. A variable of a primitive type always holds a value of that exact type. A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T. A variable of an interface type can hold a null reference or a reference to any instance of any class that implements the interface. If T is a primitive type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of T"; if T is a reference type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of S" such that type S is assignable (§5.2) to type T. A variable of type Object can hold a null reference or a reference to any object, whether class interface or array.

- -

4.1 The Kinds of Types and Values

- -There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).

-

-There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

- -

4.2 Primitive Types and Values

- -A primitive type is predefined by the Java programming language and named by its reserved keyword (§3.9):

-

-Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable.

- -The numeric types are the integral types and the floating-point types.

- -The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.

- -The floating-point types are float, whose values include the 32-bit IEEE 754 floating-point numbers, and double, whose values include the 64-bit IEEE 754 floating-point numbers.

- -The boolean type has exactly two values: true and false.

- -

4.2.1 Integral Types and Values

- -The values of the integral types are integers in the following ranges:

-

-

4.2.2 Integer Operations

- -The Java programming language provides a number of operators that act on integral values:

-

-Other useful constructors, methods, and constants are predefined in the classes Byte, Short, Integer, Long, and Character.

- -If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.4) to type long by numeric promotion (§5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

- -The built-in integer operators do not indicate overflow or underflow in any way. The only numeric operators that can throw an exception (§11) are the integer divide operator / (§15.17.2) and the integer remainder operator % (§15.17.3), which throw an ArithmeticException if the right-hand operand is zero.

- -The example: -

class Test {
-	public static void main(String[] args) {
-		int i = 1000000;
-		System.out.println(i * i);
-		long l = i;
-		System.out.println(l * l);
-		System.out.println(20296 / (l - i));
-	}
-}
-
-produces the output:

-

-727379968
-1000000000000
-
-and then encounters an ArithmeticException in the division by l - i, because l - i is zero. The first multiplication is performed in 32-bit precision, whereas the second multiplication is a long multiplication. The value -727379968 is the decimal value of the low 32 bits of the mathematical result, 1000000000000, which is a value too large for type int.

- -Any value of any integral type may be cast to or from any numeric type. There are no casts between integral types and the type boolean.

- -

4.2.3 Floating-Point Types, Formats, and Values

- -The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).

- -The IEEE 754 standard includes not only positive and negative numbers that consist of a sign and magnitude, but also positive and negative zeros, positive and negative infinities, and special Not-a-Number values (hereafter abbreviated NaN). A NaN value is used to represent the result of certain invalid operations such as dividing zero by zero. NaN constants of both float and double type are predefined as Float.NaN and Double.NaN.

- -Every implementation of the Java programming language is required to support two standard sets of floating-point values, called the float value set and the double value set. In addition, an implementation of the Java programming language may support either or both of two extended-exponent floating-point value sets, called the float-extended-exponent value set and the double-extended-exponent value set. These extended-exponent value sets may, under certain circumstances, be used instead of the standard value sets to represent the values of expressions of type float or double (§5.1.8, §15.4).

- -The finite nonzero values of any floating-point value set can all be expressed in the form , where s is +1 or -1, m is a positive integer less than , and e is an integer between and , inclusive, and where N and K are parameters that depend on the value set. Some values can be represented in this form in more than one way; for example, supposing that a value v in a value set might be represented in this form using certain values for s, m, and e, then if it happened that m were even and e were less than , one could halve m and increase e by 1 to produce a second representation for the same value v. A representation in this form is called normalized if ; otherwise the representation is said to be denormalized. If a value in a value set cannot be represented in such a way that , then the value is said to be a denormalized value, because it has no normalized representation.

- -The constraints on the parameters N and K (and on the derived parameters Emin and Emax) for the two required and two optional floating-point value sets are summarized in Table 4.1. -

- - -
-Floating-point value set parameters -
- Parameter - -float - -float-extended-exponent - - double - - double-extended-exponent - -
- N

-

- 24

-

- 24

-

- 53

-

- 53

- -

- K

-

- 8

-

- 11

-

- 11

-

- 15

- -

- Emax

-

- +127

-

- +1023

-

- +1023

-

- +16383

- -

- Emin

-

- -126

-

- -1022

-

- -1022

-

- -16382

- - -

- - -
-
-

- -Where one or both extended-exponent value sets are supported by an implementation, then for each supported extended-exponent value set there is a specific implementation-dependent constant K, whose value is constrained by Table 4.1; this value K in turn dictates the values for Emin and Emax.

- -Each of the four value sets includes not only the finite nonzero values that are ascribed to it above, but also NaN values and the four values positive zero, negative zero, positive infinity, and negative infinity.

- -Note that the constraints in Table 4.1 are designed so that every element of the float value set is necessarily also an element of the float-extended-exponent value set, the double value set, and the double-extended-exponent value set. Likewise, each element of the double value set is necessarily also an element of the double-extended-exponent value set. Each extended-exponent value set has a larger range of exponent values than the corresponding standard value set, but does not have more precision.

- -The elements of the float value set are exactly the values that can be represented using the single floating-point format defined in the IEEE 754 standard. The elements of the double value set are exactly the values that can be represented using the double floating-point format defined in the IEEE 754 standard. Note, however, that the elements of the float-extended-exponent and double-extended-exponent value sets defined here do not correspond to the values that can be represented using IEEE 754 single extended and double extended formats, respectively.

- -The float, float-extended-exponent, double, and double-extended-exponent value sets are not types. It is always correct for an implementation of the Java programming language to use an element of the float value set to represent a value of type float; however, it may be permissible in certain regions of code for an implementation to use an element of the float-extended-exponent value set instead. Similarly, it is always correct for an implementation to use an element of the double value set to represent a value of type double; however, it may be permissible in certain regions of code for an implementation to use an element of the double-extended-exponent value set instead.

- -Except for NaN, floating-point values are ordered; arranged from smallest to largest, they are negative infinity, negative finite nonzero values, positive and negative zero, positive finite nonzero values, and positive infinity.

- -IEEE 754 allows multiple distinct NaN values for each of its single and double floating-point formats. While each hardware architecture returns a particular bit pattern for NaN when a new NaN is generated, a programmer can also create NaNs with different bit patterns to encode, for example, retrospective diagnostic information.

- -For the most part, the Java platform treats NaN values of a given type as though collapsed into a single canonical value (and hence this specification normally refers to an arbitrary NaN as though to a canonical value). However, version 1.3 the Java platform introduced methods enabling the programmer to distinguish between NaN values: the Float.floatToRawIntBits and Double.doubleToRawLongBits methods. The interested reader is referred to the specifications for the Float and Double classes for more information.

- -Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity.

- -NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.

- -Any value of a floating-point type may be cast to or from any numeric type. There are no casts between floating-point types and the type boolean.

- -

4.2.4 Floating-Point Operations

- -The Java programming language provides a number of operators that act on floating-point values:

-

-Other useful constructors, methods, and constants are predefined in the classes Float, Double, and Math.

- -If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

- -If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. (If the other operand is not a double, it is first widened to type double by numeric promotion (§5.6).) Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. If the other operand is not a float, it is first widened to type float by numeric promotion.

- -Operators on floating-point numbers behave as specified by IEEE 754 (with the exception of the remainder operator (§15.17.3)). In particular, the Java programming language requires support of IEEE 754 denormalized floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations do not "flush to zero" if the calculated result is a denormalized number.

- -The Java programming language requires that floating-point arithmetic behave as if every floating-point operator rounded its floating-point result to the result precision. Inexact results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, the one with its least significant bit zero is chosen. This is the IEEE 754 standard's default rounding mode known as round to nearest.

- -The language uses round toward zero when converting a floating value to an integer (§5.1.3), which acts, in this case, as though the number were truncated, discarding the mantissa bits. Rounding toward zero chooses at its result the format's value closest to and no greater in magnitude than the infinitely precise result.

- -Floating-point operators produce no exceptions (§11). An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN.

- -The example program: -

class Test {
-	public static void main(String[] args) {
-		// An example of overflow:
-		double d = 1e308;
-		System.out.print("overflow produces infinity: ");
-		System.out.println(d + "*10==" + d*10);
-		// An example of gradual underflow:
-		d = 1e-305 * Math.PI;
-		System.out.print("gradual underflow: " + d + "\n      ");
-		for (int i = 0; i < 4; i++)
-			System.out.print(" " + (d /= 100000));
-		System.out.println();
-		// An example of NaN:
-		System.out.print("0.0/0.0 is Not-a-Number: ");
-		d = 0.0/0.0;
-		System.out.println(d);
-		// An example of inexact results and rounding:
-		System.out.print("inexact results with float:");
-		for (int i = 0; i < 100; i++) {
-			float z = 1.0f / i;
-			if (z * i != 1.0f)
-				System.out.print(" " + i);
-		}
-		System.out.println();
-		// Another example of inexact results and rounding:
-		System.out.print("inexact results with double:");
-		for (int i = 0; i < 100; i++) {
-			double z = 1.0 / i;
-			if (z * i != 1.0)
-				System.out.print(" " + i);
-		}
-		System.out.println();
-		// An example of cast to integer rounding:
-		System.out.print("cast to int rounds toward 0: ");
-		d = 12345.6;
-		System.out.println((int)d + " " + (int)(-d));
-	}
-}
-
-produces the output:

-

overflow produces infinity: 1.0e+308*10==Infinity
-gradual underflow: 3.141592653589793E-305
-	3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0
-0.0/0.0 is Not-a-Number: NaN
-inexact results with float: 0 41 47 55 61 82 83 94 97
-inexact results with double: 0 49 98
-cast to int rounds toward 0: 12345 -12345
-
- -This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision. - -The results when i is 0 involve division by zero, so that z becomes positive infinity, and z * 0 is NaN, which is not equal to 1.0. - -

4.2.5 The boolean Type and boolean Values

- -The boolean type represents a logical quantity with two possible values, indicated by the literals true and false (§3.10.3). The boolean operators are:

-

-Boolean expressions determine the control flow in several kinds of statements:

-

-A boolean expression also determines which subexpression is evaluated in the conditional ? : operator (§15.25).

- -Only boolean expressions can be used in control flow statements and as the first operand of the conditional operator ? :. An integer x can be converted to a boolean, following the C language convention that any nonzero value is true, by the expression x!=0. An object reference obj can be converted to a boolean, following the C language convention that any reference other than null is true, by the expression obj!=null.

- -A cast of a boolean value to type boolean is allowed (§5.1.1); no other casts on type boolean are allowed. A boolean can be converted to a string by string conversion (§5.4).

- -

4.3 Reference Types and Values

- -There are three kinds of reference types: class types (§8), interface types (§9), and array types (§10).

-

-Names are described in §6; type names in §6.5 and, specifically, §6.5.5.

- -The sample code: -

class Point { int[] metrics; }
-interface Move { void move(int deltax, int deltay); }
-
-declares a class type Point, an interface type Move, and uses an array type int[] (an array of int) to declare the field metrics of the class Point.

- -

4.3.1 Objects

- -An object is a class instance or an array.

- -The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

- -A class instance is explicitly created by a class instance creation expression (§15.9). An array is explicitly created by an array creation expression (§15.9).

- -A new class instance is implicitly created when the string concatenation operator + (§15.18.1) is used in an expression, resulting in a new object of type String (§4.3.3). A new array object is implicitly created when an array initializer expression (§10.6) is evaluated; this can occur when a class or interface is initialized (§12.4), when a new instance of a class is created (§15.9), or when a local variable declaration statement is executed (§14.4).

- -Many of these cases are illustrated in the following example: -

class Point {
-	int x, y;
-	Point() { System.out.println("default"); }
-	Point(int x, int y) { this.x = x; this.y = y; }
-	// A Point instance is explicitly created at class initialization time:
-	static Point origin = new Point(0,0);
-	// A String can be implicitly created by a + operator:
-	public String toString() {
-		return "(" + x + "," + y + ")";
-	}
-}
-class Test {
-	public static void main(String[] args) {
-		// A Point is explicitly created using newInstance:
-		Point p = null;
-		try {
-			p = (Point)Class.forName("Point").newInstance();
-		} catch (Exception e) {
-			System.out.println(e);
-		}
-		// An array is implicitly created by an array constructor:
-		Point a[] = { new Point(0,0), new Point(1,1) };
-		// Strings are implicitly created by + operators:
-		System.out.println("p: " + p);
-		System.out.println("a: { " + a[0] + ", "
-										   + a[1] + " }");
-		// An array is explicitly created by an array creation expression:
-		String sa[] = new String[2];
-		sa[0] = "he"; sa[1] = "llo";
-		System.out.println(sa[0] + sa[1]);
-	}
-}
-
-which produces the output:

-

default
-p: (0,0)
-a: { (0,0), (1,1) }
-hello
-
-The operators on references to objects are:

-

-There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.

- -The example program: -

class Value { int val; }
-class Test {
-	public static void main(String[] args) {
-		int i1 = 3;
-		int i2 = i1;
-		i2 = 4;
-		System.out.print("i1==" + i1);
-		System.out.println(" but i2==" + i2);
-		Value v1 = new Value();
-		v1.val = 5;
-		Value v2 = v1;
-		v2.val = 6;
-		System.out.print("v1.val==" + v1.val);
-		System.out.println(" and v2.val==" + v2.val);
-	}
-}
-
-produces the output:

-

i1==3 but i2==4
-v1.val==6 and v2.val==6
-
-because v1.val and v2.val reference the same instance variable (§4.5.3) in the one Value object created by the only new expression, while i1 and i2 are different variables.

- -See §10 and §15.10 for examples of the creation and use of arrays. - -Each object has an associated lock (§17.13), which is used by synchronized methods (§8.4.3) and the synchronized statement (§14.18) to provide control over concurrent access to state by multiple threads (§17.12).

- -

4.3.2 The Class Object

- -The class Object is a superclass (§8.1) of all other classes. A variable of type Object can hold a reference to any object, whether it is an instance of a class or an array (§10). All class and array types inherit the methods of class Object, which are summarized here:

-

package java.lang;
-
-public class Object {
-	public final Class getClass() { . . . }
-	public String toString() { . . . }
-	public boolean equals(Object obj) { . . . }
-	public int hashCode() { . . . }
-	protected Object clone()
-		throws CloneNotSupportedException { . . . }
-	public final void wait()
-		throws IllegalMonitorStateException,
-			InterruptedException { . . . }
-	public final void wait(long millis)
-		throws IllegalMonitorStateException,
-			InterruptedException { . . . }
-	public final void wait(long millis, int nanos) { . . . }
-		throws IllegalMonitorStateException,
-			InterruptedException { . . . }
-	public final void notify() { . . . }
-		throws IllegalMonitorStateException
-	public final void notifyAll() { . . . }
-		throws IllegalMonitorStateException
-	protected void finalize()
-		throws Throwable { . . . }
-}
-
-The members of Object are as follows:

-

-

4.3.3 The Class String

- -Instances of class String represent sequences of Unicode characters. A String object has a constant (unchanging) value. String literals (§3.10.5) are references to instances of class String.

- -The string concatenation operator + (§15.18.1) implicitly creates a new String object.

- -

4.3.4 When Reference Types Are the Same

- -Two reference types are the same compile-time type if they have the same binary name (§13.1), in which case they are sometimes said to be the same class or the same interface.

- -At run time, several reference types with the same binary name may be loaded simultaneously by different class loaders. These types may or may not represent the same type declaration. Even if two such types do represent the same type declaration, they are considered distinct.

- -Two reference types are the same run-time type if:

-

-

4.4 Where Types Are Used

- -Types are used when they appear in declarations or in certain expressions.

- -The following code fragment contains one or more instances of most kinds of usage of a type: -

import java.util.Random;
-class MiscMath {
-	int divisor;
-	MiscMath(int divisor) {
-		this.divisor = divisor;
-	}
-	float ratio(long l) {
-		try {
-			l /= divisor;
-		} catch (Exception e) {
-			if (e instanceof ArithmeticException)
-				l = Long.MAX_VALUE;
-			else
-				l = 0;
-		}
-		return (float)l;
-	}
-	double gausser() {
-		Random r = new Random();
-		double[] val = new double[2];
-		val[0] = r.nextGaussian();
-		val[1] = r.nextGaussian();
-		return (val[0] + val[1]) / 2;
-	}
-}
-
-In this example, types are used in declarations of the following:

-

-and in expressions of the following kinds:

-

-

4.5 Variables

- -A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3). A variable always contains a value that is assignment compatible (§5.2) with its type. A variable's value is changed by an assignment (§15.26) or by a prefix or postfix ++ (increment) or -- (decrement) operator (§15.14.1, §15.14.2, §15.15.1, §15.15.2).

- -Compatibility of the value of a variable with its type is guaranteed by the design of the Java programming language. Default values are compatible (§4.5.5) and all assignments to a variable are checked for assignment compatibility (§5.2), usually at compile time, but, in a single case involving arrays, a run-time check is made (§10.10).

- -

4.5.1 Variables of Primitive Type

- -A variable of a primitive type always holds a value of that exact primitive type.

- -

4.5.2 Variables of Reference Type

- -A variable of reference type can hold either of the following:

-

-

4.5.3 Kinds of Variables

- -There are seven kinds of variables:

-

    - -
  1. A class variable is a field declared using the keyword static within a class declaration (§8.3.1.1), or with or without the keyword static within an interface declaration (§9.3). A class variable is created when its class or interface is prepared (§12.3.2) and is initialized to a default value (§4.5.5). The class variable effectively ceases to exist when its class or interface is unloaded (§12.7). - -
  2. An instance variable is a field declared within a class declaration without using the keyword static (§8.3.1.1). If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.5.5) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.3). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed. - -
  3. Array components are unnamed variables that are created and initialized to default values (§4.5.5) whenever a new object that is an array is created (§15.10). The array components effectively cease to exist when the array is no longer referenced. See §10 for a description of arrays. - -
  4. Method parameters (§8.4.1) name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked (§15.12). The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete. - -
  5. Constructor parameters (§8.8.1) name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression (§15.9) or explicit constructor invocation (§8.8.5) invokes that constructor. The new variable is initialized with the corresponding argument value from the creation expression or constructor invocation. The constructor parameter effectively ceases to exist when the execution of the body of the constructor is complete. - -
  6. An exception-handler parameter is created each time an exception is caught by a catch clause of a try statement (§14.19). The new variable is initialized with the actual object associated with the exception (§11.3, §14.17). The exception-handler parameter effectively ceases to exist when execution of the block associated with the catch clause is complete. - -
  7. Local variables are declared by local variable declaration statements (§14.4). Whenever the flow of control enters a block (§14.2) or for statement (§14.13), a new variable is created for each local variable declared in a local variable declaration statement immediately contained within that block or for statement. A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (§16) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or for statement is complete. -
-Were it not for one exceptional situation, a local variable could always be regarded as being created when its local variable declaration statement is executed. The exceptional situation involves the switch statement (§14.10), where it is possible for control to enter a block but bypass execution of a local variable declaration statement. Because of the restrictions imposed by the rules of definite assignment (§16), however, the local variable declared by such a bypassed local variable declaration statement cannot be used before it has been definitely assigned a value by an assignment expression (§15.26). - -The following example contains several different kinds of variables: -
-class Point {
-	static int numPoints;		// numPoints is a class variable
-	int x, y;			// x and y are instance variables
-	int[] w = new int[10];		// w[0] is an array component
-	int setX(int x) {		// x is a method parameter
-		int oldx = this.x;	// oldx is a local variable
-		this.x = x;
-		return oldx;
-	}
-}
-
-

4.5.4 final Variables

- -A variable can be declared final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

- -A blank final is a final variable whose declaration lacks an initializer.

- -Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object. This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.

- -Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors. - -

In the example: -

class Point {
-	int x, y;
-	int useCount;
-	Point(int x, int y) { this.x = x; this.y = y; }
-	final static Point origin = new Point(0, 0);
-}
-
-the class Point declares a final class variable origin. The origin variable holds a reference to an object that is an instance of class Point whose coordinates are (0, 0). The value of the variable Point.origin can never change, so it always refers to the same Point object, the one created by its initializer. However, an operation on this Point object might change its state-for example, modifying its useCount or even, misleadingly, its x or y coordinate.

- -

4.5.5 Initial Values of Variables

- -Every variable in a program must have a value before its value is used:

-

-The example program:

-

class Point {
-	static int npoints;
-	int x, y;
-	Point root;
-}
-class Test {
-	public static void main(String[] args) {
-		System.out.println("npoints=" + Point.npoints);
-		Point p = new Point();
-		System.out.println("p.x=" + p.x + ", p.y=" + p.y);
-		System.out.println("p.root=" + p.root);
-	}
-}
-
-prints:

-

npoints=0
-p.x=0, p.y=0
-p.root=null
-
-illustrating the default initialization of npoints, which occurs when the class Point is prepared (§12.3.2), and the default initialization of x, y, and root, which occurs when a new Point is instantiated. See §12 for a full description of all aspects of loading, linking, and initialization of classes and interfaces, plus a description of the instantiation of classes to make new class instances.

- -

4.5.6 Types, Classes, and Interfaces

- -In the Java programming language, every variable and every expression has a type that can be determined at compile time. The type may be a primitive type or a reference type. Reference types include class types and interface types. Reference types are introduced by type declarations, which include class declarations (§8.1) and interface declarations (§9.1). We often use the term type to refer to either a class or an interface.

- -Every object belongs to some particular class: the class that was mentioned in the creation expression that produced the object, the class whose Class object was used to invoke a reflective method to produce the object, or the String class for objects implicitly created by the string concatenation operator + (§15.18.1). This class is called the class of the object. (Arrays also have a class, as described at the end of this section.) An object is said to be an instance of its class and of all superclasses of its class.

- -Sometimes a variable or expression is said to have a "run-time type". This refers to the class of the object referred to by the value of the variable or expression at run time, assuming that the value is not null.

- -The compile time type of a variable is always declared, and the compile time type of an expression can be deduced at compile time. The compile time type limits the possible values that the variable can hold or the expression can produce at run time. If a run-time value is a reference that is not null, it refers to an object or array that has a class, and that class will necessarily be compatible with the compile-time type.

- -Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (§8.1.4) that interface.

- -Here is an example of creating new objects and of the distinction between the type of a variable and the class of an object: -

public interface Colorable {
-	void setColor(byte r, byte g, byte b);
-}
-class Point { int x, y; }
-class ColoredPoint extends Point implements Colorable {
-	byte r, g, b;
-	public void setColor(byte rv, byte gv, byte bv) {
-		r = rv; g = gv; b = bv;
-	}
-}
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		ColoredPoint cp = new ColoredPoint();
-		p = cp;
-		Colorable c = cp;
-	}
-}
-
-In this example:

-

-Every array also has a class; the method getClass, when invoked for an array object, will return a class object (of class Class) that represents the class of the array.

- -The classes for arrays have strange names that are not valid identifiers; for example, the class for an array of int components has the name "[I" and so the value of the expression: -

new int[10].getClass().getName()
-
-is the string "[I"; see the specification of Class.getName for details.

- - -


- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - - - - Names - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 6

- -

Names

-

- -Names are used to refer to entities declared in a program. A declared entity (§6.1) is a package, class type, interface type, member (class, interface, field, or method) of a reference type, parameter (to a method, constructor, or exception handler), or local variable.

- -Names in programs are either simple, consisting of a single identifier, or qualified, consisting of a sequence of identifiers separated by "." tokens (§6.2).

- -Every declaration that introduces a name has a scope (§6.3), which is the part of the program text within which the declared entity can be referred to by a simple name.

- -Packages and reference types (that is, class types, interface types, and array types) have members (§6.4). A member can be referred to using a qualified name N.x, where N is a simple or qualified name and x is an identifier. If N names a package, then x is a member of that package, which is either a class or interface type or a subpackage. If N names a reference type or a variable of a reference type, then x names a member of that type, which is either a class, an interface, a field, or a method.

- -In determining the meaning of a name (§6.5), the context of the occurrence is used to disambiguate among packages, types, variables, and methods with the same name.

- -Access control (§6.6) can be specified in a class, interface, method, or field declaration to control when access to a member is allowed. Access is a different concept from scope; access specifies the part of the program text within which the declared entity can be referred to by a qualified name, a field access expression (§15.11), or a method invocation expression (§15.12) in which the method is not specified by a simple name. The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are public, protected, and private.

- -Fully qualified and canonical names (§6.7) and naming conventions (§6.8) are also discussed in this chapter.

- -The name of a field, parameter, or local variable may be used as an expression (§15.14.1). The name of a method may appear in an expression only as part of a method invocation expression (§15.12). The name of a class or interface type may appear in an expression only as part of a class literal (§15.8.2), a qualified this expression (§15.8.4), a class instance creation expression (§15.9), an array creation expression (§15.10), a cast expression (§15.16), or an instanceof expression (§15.20.2), or as part of a qualified name for a field or method. The name of a package may appear in an expression only as part of a qualified name for a class or interface type.

- -

6.1 Declarations

- -A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:

-

-Constructors (§8.8) are also introduced by declarations, but use the name of the class in which they are declared rather than introducing a new name.

- -

6.2 Names and Identifiers

- -A name is used to refer to an entity declared in a program.

- -There are two forms of names: simple names and qualified names. A simple name is a single identifier. A qualified name consists of a name, a "." token, and an identifier.

- -In determining the meaning of a name (§6.5), the context in which the name appears is taken into account. The rules of §6.5 distinguish among contexts where a name must denote (refer to) a package (§6.5.3), a type (§6.5.5), a variable or value in an expression (§6.5.6), or a method (§6.5.7).

- -Not all identifiers in programs are a part of a name. Identifiers are also used in the following situations:

-

-In the example:

-

class Test {
-	public static void main(String[] args) {
-		Class c = System.out.getClass();
-		System.out.println(c.toString().length() +
-					args[0].length() + args.length);
-	}
-}
-
-the identifiers Test, main, and the first occurrences of args and c are not names; rather, they are used in declarations to specify the names of the declared entities. The names String, Class, System.out.getClass, System.out.println, c.toString, args, and args.length appear in the example. The first occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.12). The second occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.12).

- -The identifiers used in labeled statements and their associated break and continue statements are completely separate from those used in declarations. Thus, the following code is valid: -

class TestString {
-	char[] value;
-	int offset, count;
-	int indexOf(TestString str, int fromIndex) {
-		char[] v1 = value, v2 = str.value;
-		int max = offset + (count - str.count);
-		int start = offset + ((fromIndex < 0) ? 0 : fromIndex);
-	i:
-		for (int i = start; i <= max; i++)
-		{
-			int n = str.count, j = i, k = str.offset;
-			while (n-- != 0) {
-				if (v1[j++] != v2[k++])
-					continue i;
-			} 
-			return i - offset;
-		}
-		return -1;
-	}
-}
-
-This code was taken from a version of the class String and its method indexOf, where the label was originally called test. Changing the label to have the same name as the local variable i does not obscure (§6.3.2) the label in the scope of the declaration of i. The identifier max could also have been used as the statement label; the label would not obscure the local variable max within the labeled statement.

- -

6.3 Scope of a Declaration

- -The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name (provided it is visible (§6.3.1)). A declaration is said to be in scope at a particular point in a program if and only if the declaration's scope includes that point.

- -The scoping rules for various constructs are given in the sections that describe those constructs. For convenience, the rules are repeated here:

- - The scope of the declaration of an observable (§7.4.3) top level package is all observable compilation units (§7.3). The declaration of a package that is not observable is never in scope. Subpackage declarations are never in scope.

- -The scope of a type imported by a single-type-import declaration (§7.5.1) or type-import-on-demand declaration (§7.5.2) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.

- -The scope of a top level type is all type declarations in the package in which the top level type is declared.

- -The scope of a label declared by a labeled statement is the statement immediately enclosed by the labeled statement.

- -The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, including any nested type declarations.

- -The scope of the declaration of a member m declared in or inherited by an interface type I is the entire body of I, including any nested type declarations.

- -The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.

- -The scope of a local variable declaration in a block (§14.4.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

- -The scope of a local class declared in a block is the rest of the immediately enclosing block, including its own class declaration.

- -The scope of a local variable declared in the ForInit part of a for statement (§14.13) includes all of the following:

-

-The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (§14.19) is the entire block associated with the catch.

- -These rules imply that declarations of class and interface types need not appear before uses of the types.

- -In the example: -

package points;
-class Point {
-	int x, y;
-	PointList list;
-	Point next;
-}
-class PointList {
-	Point first;
-}
-
-the use of PointList in class Point is correct, because the scope of the class declaration PointList includes both class Point and class PointList, as well as any other type declarations in other compilation units of package points.

- -

6.3.1 Shadowing Declarations

- -Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.

- -A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d.

- -A declaration d of a field, local variable, method parameter, constructor parameter or exception handler parameter named n shadows the declarations of any other fields, local variables, method parameters, constructor parameters or exception handler parameters named n that are in scope at the point where d occurs throughout the scope of d.

- -A declaration d of a label named n shadows the declarations of any other labels named n that are in scope at the point where d occurs throughout the scope of d.

- -A declaration d of a method named n shadows the declarations of any other methods named n that are in an enclosing scope at the point where d occurs throughout the scope of d.

- -A package declaration never shadows any other declaration.

- -A single-type-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

-

-throughout c.

- -A type-import-on-demand declaration never causes any other declaration to be shadowed.

- -A declaration d is said to be visible at point p in a program if the scope of d includes p, and d is not shadowed by any other declaration at p. When the program point we are discussing is clear from context, we will often simply say that a declaration is visible.

- -Note that shadowing is distinct from hiding (§8.3, §8.4.6.2, §8.5, §9.3, §9.5). Hiding, in the technical sense defined in this specification, applies only to members which would otherwise be inherited but are not because of a declaration in a subclass. Shadowing is also distinct from obscuring (§6.3.2). -

- -Here is an example of shadowing of a field declaration by a local variable declaration: -

class Test {
-	static int x = 1;
-	public static void main(String[] args) {
-		int x = 0;
-		System.out.print("x=" + x);
-		System.out.println(", Test.x=" + Test.x);
-	}
-}
-
-produces the output:

-

x=0, Test.x=1
-
-This example declares:

-

-Since the scope of a class variable includes the entire body of the class (§8.2) the class variable x would normally be available throughout the entire body of the method main. In this example, however, the class variable x is shadowed within the body of the method main by the declaration of the local variable x. -

- -A local variable has as its scope the rest of the block in which it is declared (§14.4.2); in this case this is the rest of the body of the main method, namely its initializer "0" and the invocations of print and println. - -

-This means that: - -

-The following example illustrates the shadowing of one type declaration by another: -
import java.util.*;
-class Vector {
-	int val[] = { 1 , 2 };
-
-}

-class Test { - public static void main(String[] args) { - Vector v = new Vector(); - System.out.println(v.val[0]); - } -} -

-compiles and prints:

-

1
-
-using the class Vector declared here in preference to class java.util.Vector that might be imported on demand.

- -

6.3.2 Obscured Declarations

- -A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.

- -Obscuring is distinct from shadowing (§6.3.1) and hiding (§8.3, §8.4.6.2, §8.5, §9.3, §9.5). The naming conventions of §6.8 help reduce obscuring. -

- -

6.4 Members and Inheritance

- -Packages and reference types have members.

- -This section provides an overview of the members of packages and reference types here, as background for the discussion of qualified names and the determination of the meaning of names. For a complete description of membership, see §7.1, §8.2, §9.2, and §10.7. -

- -

6.4.1 The Members of a Package

- -The members of a package (§7) are specified in §7.1. For convenience, we repeat that specification here:

- -The members of a package are subpackages and all the top level (§7.6) class (§8) and top level interface (§9) types declared in all the compilation units (§7.3) of the package.

- -In general, the subpackages of a package are determined by the host system (§7.2). However, the package java always includes the subpackages lang and io and may include other subpackages. No two distinct members of the same package may have the same simple name (§7.1), but members of different packages may have the same simple name.

- -For example, it is possible to declare a package: -

package vector;
-public class Vector { Object[] vec; }
-
-that has as a member a public class named Vector, even though the package java.util also declares a class named Vector. These two class types are different, reflected by the fact that they have different fully qualified names (§6.7). The fully qualified name of this example Vector is vector.Vector, whereas java.util.Vector is the fully qualified name of the standard Vector class. Because the package vector contains a class named Vector, it cannot also have a subpackage named Vector.

- -

6.4.2 The Members of a Class Type

- -The members of a class type (§8.2) are classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4). Members are either declared in the type, or inherited because they are accessible members of a superclass or superinterface which are neither private nor hidden nor overridden (§8.4.6).

- -The members of a class type are all of the following: -

-Constructors (§8.8) are not members.

- -There is no restriction against a field and a method of a class type having the same simple name. Likewise, there is no restriction against a member class or member interface of a class type having the same simple name as a field or method of that class type. - -

-A class may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error (§6.5.7.2, §8.2). - -

-In the example: -

interface Colors {
-	int WHITE = 0, BLACK = 1;
-}
-interface Separates {
-	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
-}
-class Test implements Colors, Separates {
-	public static void main(String[] args) {
-		System.out.println(BLACK); // compile-time error: ambiguous
-	}
-}
-
-the name BLACK in the method main is ambiguous, because class Test has two members named BLACK, one inherited from Colors and one from Separates.

- -A class type may have two or more methods with the same simple name if the methods have different signatures (§8.4.2), that is, if they have different numbers of parameters or different parameter types in at least one parameter position. Such a method member name is said to be overloaded. -

- -A class type may contain a declaration for a method with the same name and the same signature as a method that would otherwise be inherited from a superclass or superinterface. In this case, the method of the superclass or superinterface is not inherited. If the method not inherited is abstract, then the new declaration is said to implement it; if the method not inherited is not abstract, then the new declaration is said to override it.

- -In the example: -

class Point {
-	float x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	void move(float dx, float dy) { x += dx; y += dy; }
-	public String toString() { return "("+x+","+y+")"; }
-}
-
-the class Point has two members that are methods with the same name, move. The overloaded move method of class Point chosen for any particular method invocation is determined at compile time by the overloading resolution procedure given in §15.12.

- -In this example, the members of the class Point are the float instance variables x and y declared in Point, the two declared move methods, the declared toString method, and the members that Point inherits from its implicit direct superclass Object (§4.3.2), such as the method hashCode. Note that Point does not inherit the toString method of class Object because that method is overridden by the declaration of the toString method in class Point. -

- -

6.4.3 The Members of an Interface Type

- -The members of an interface type (§9.2) may be classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4).The members of an interface are:

-

-An interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any such field by its simple name results in a compile-time error (§6.5.6.1, §9.2).

- -In the example: -

interface Colors {
-	int WHITE = 0, BLACK = 1;
-}
-interface Separates {
-	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
-}
-interface ColorsAndSeparates extends Colors, Separates {
-	int DEFAULT = BLACK;								 	// compile-time error: ambiguous
-}
-
-the members of the interface ColorsAndSeparates include those members inherited from Colors and those inherited from Separates, namely WHITE, BLACK (first of two), CYAN, MAGENTA, YELLOW, and BLACK (second of two). The member name BLACK is ambiguous in the interface ColorsAndSeparates.

- -

6.4.4 The Members of an Array Type

- -The members of an array type are specified in §10.7. For convenience, we repeat that specification here.

- -The members of an array type are all of the following:

-

-

- -The example:

-

class Test {
-	public static void main(String[] args) {
-		int[] ia = new int[3];
-		int[] ib = new int[6];
-		System.out.println(ia.getClass() == ib.getClass());
-		System.out.println("ia has length=" + ia.length);
-	}
-}
-
-produces the output:

-

true
-ia has length=3
-
-This example uses the method getClass inherited from class Object and the field length. The result of the comparison of the Class objects in the first println demonstrates that all arrays whose components are of type int are instances of the same array type, which is int[].

- -

6.5 Determining the Meaning of a Name

- -The meaning of a name depends on the context in which it is used. The determination of the meaning of a name requires three steps. First, context causes a name syntactically to fall into one of six categories: PackageName, TypeName, ExpressionName, MethodName, PackageOrTypeName, or AmbiguousName. Second, a name that is initially classified by its context as an AmbiguousName or as a Package-OrTypeName is then reclassified to be a PackageName, TypeName, or ExpressionName. Third, the resulting category then dictates the final determination of the meaning of the name (or a compilation error if the name has no meaning).

-

- -The use of context helps to minimize name conflicts between entities of different kinds. Such conflicts will be rare if the naming conventions described in §6.8 are followed. Nevertheless, conflicts may arise unintentionally as types developed by different programmers or different organizations evolve. For example, types, methods, and fields may have the same name. It is always possible to distinguish between a method and a field with the same name, since the context of a use always tells whether a method is intended. - -

6.5.1 Syntactic Classification of a Name According to Context

- -A name is syntactically classified as a PackageName in these contexts:

-

-A name is syntactically classified as a TypeName in these contexts:

-

-A name is syntactically classified as an ExpressionName in these contexts:

-

-A name is syntactically classified as a MethodName in this context:

-

-A name is syntactically classified as a PackageOrTypeName in these contexts:

-

-A name is syntactically classified as an AmbiguousName in these contexts:

-

-

6.5.2 Reclassification of Contextually Ambiguous Names

- -An AmbiguousName is then reclassified as follows:

-

package org.rpgpoet;
-import java.util.Random;
-interface Music { Random[] wizards = new Random[4]; }
-
-and then consider this example code in another package:

-

package bazola;
-class Gabriel {
-	static int n = org.rpgpoet.Music.wizards.length;
-}
-
-First of all, the name org.rpgpoet.Music.wizards.length is classified as an ExpressionName because it functions as a PostfixExpression. Therefore, each of the names:

- -

org.rpgpoet.Music.wizards
-org.rpgpoet.Music
-org.rpgpoet
-org 
-
-is initially classified as an AmbiguousName. These are then reclassified:

-

-

6.5.3 Meaning of Package Names

- -The meaning of a name classified as a PackageName is determined as follows.

- -

6.5.3.1 Simple Package Names

- -If a package name consists of a single Identifier, then this identifier denotes a top level package named by that identifier. If no top level package of that name is in scope (§7.4.4), then a compile-time error occurs.

- -

6.5.3.2 Qualified Package Names

- -If a package name is of the form Q.Id, then Q must also be a package name. The package name Q.Id names a package that is the member named Id within the package named by Q. If Q does not name an observable package (§7.4.3), or Id is not the simple name an observable subpackage of that package, then a compile-time error occurs.

- -

6.5.4 Meaning of PackageOrTypeNames

- -

6.5.4.1 Simple PackageOrTypeNames

- -If the PackageOrTypeName, Q, occurs in the scope of a type named Q, then the PackageOrTypeName is reclassified as a TypeName.

- -Otherwise, the PackageOrTypeName is reclassified as a PackageName. The meaning of the PackageOrTypeName is the meaning of the reclassified name.

- -

6.5.4.2 Qualified PackageOrTypeNames

- -Given a qualified PackageOrTypeName of the form Q.Id, if the type or package denoted by Q has a member type named Id, then the qualified PackageOrTypeName name is reclassified as a TypeName.

- -Otherwise, it is reclassified as a PackageName. The meaning of the qualified PackageOrTypeName is the meaning of the reclassified name.

- -

6.5.5 Meaning of Type Names

- -The meaning of a name classified as a TypeName is determined as follows.

- -

6.5.5.1 Simple Type Names

- -If a type name consists of a single Identifier, then the identifier must occur in the scope of a declaration of a type with this name, or a compile-time error occurs.

- -It is possible that the identifier occurs within the scope of more than one type with that name, in which case the type denoted by the name is determined as follows:

-

-This order for considering type declarations is designed to choose the most explicit of two or more applicable type declarations.

- -

6.5.5.2 Qualified Type Names

- -If a type name is of the form Q.Id, then Q must be either a type name or a package name. If Id names exactly one type that is a member of the type or package denoted by Q, then the qualified type name denotes that type. If Id does not name a member type (§8.5, §9.5) within Q, or the member type named Id within Q is not accessible (§6.6), or Id names more than one member type within Q, then a compile-time error occurs.

- -The example: -

package wnj.test;
-class Test {
-	public static void main(String[] args) {
-		java.util.Date date =
-			new java.util.Date(System.currentTimeMillis());
-		System.out.println(date.toLocaleString());
-	}
-}
-
-produced the following output the first time it was run:

-

Sun Jan 21 22:56:29 1996
-
-In this example the name java.util.Date must denote a type, so we first use the procedure recursively to determine if java.util is an accessible type or a package, which it is, and then look to see if the type Date is accessible in this package.

- -

6.5.6 Meaning of Expression Names

- -The meaning of a name classified as an ExpressionName is determined as follows.

- -

6.5.6.1 Simple Expression Names

- -If an expression name consists of a single Identifier, then:

-

- -In the example:

-

class Test {
-	static int v;
-	static final int f = 3;
-	public static void main(String[] args) {
-		int i;
-		i = 1;
-		v = 2;
-		f = 33;										// compile-time error
-		System.out.println(i + " " + v + " " + f);
-	}
-}
-
-the names used as the left-hand-sides in the assignments to i, v, and f denote the local variable i, the field v, and the value of f (not the variable f, because f is a final variable). The example therefore produces an error at compile time because the last assignment does not have a variable as its left-hand side. If the erroneous assignment is removed, the modified code can be compiled and it will produce the output:

-

1 2 3
-
-

6.5.6.2 Qualified Expression Names

- -If an expression name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name:

-

class Point {
-	int x, y;
-	static int nPoints;
-}
-class Test {
-	public static void main(String[] args) {
-		int i = 0;
-		i.x++;			// compile-time error
-		Point p = new Point();
-		p.nPoints();	// compile-time error
-	}
-}
-
-encounters two compile-time errors, because the int variable i has no members, and because nPoints is not a method of class Point.

- -

6.5.7 Meaning of Method Names

- -A MethodName can appear only in a method invocation expression (§15.12). The meaning of a name classified as a MethodName is determined as follows.

- -

6.5.7.1 Simple Method Names

- -If a method name consists of a single Identifier, then Identifier is the method name to be used for method invocation. The Identifier must name at least one method of a class or interface within whose declaration the Identifier appears. See §15.12 for further discussion of the interpretation of simple method names in method invocation expressions.

- -

6.5.7.2 Qualified Method Names

- -If a method name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name. If Q is a package name, then a compile-time error occurs. Otherwise, Id is the method name to be used for method invocation. If Q is a type name, then Id must name at least one static method of the type Q. If Q is an expression name, then let T be the type of the expression Q; Id must name at least one method of the type T. See §15.12 for further discussion of the interpretation of qualified method names in method invocation expressions.

- -

6.6 Access Control

- -The Java programming language provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. If access is permitted, then the accessed entity is said to be accessible.

- -Note that accessibility is a static property that can be determined at compile time; it depends only on types and declaration modifiers. Qualified names are a means of access to members of packages and reference types; related means of access include field access expressions (§15.11) and method invocation expressions (§15.12). All three are syntactically similar in that a "." token appears, preceded by some indication of a package, type, or expression having a type and followed by an Identifier that names a member of the package or type. These are collectively known as constructs for qualified access.

- -Access control applies to qualified access and to the invocation of constructors by class instance creation expressions (§15.9) and explicit constructor invocations (§8.8.5). Accessibility also affects inheritance of class members (§8.2), including hiding and method overriding (§8.4.6.1).

- -

6.6.1 Determining Accessibility

- -

6.6.2 Details on protected Access

- -A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

- -

6.6.2.1 Access to a protected Member

- -Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:

-

-

6.6.2.2 Qualified Access to a protected Constructor

- -Let C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. Then:

-

-

6.6.3 An Example of Access Control

- -For examples of access control, consider the two compilation units:

-

package points;
-class PointVec { Point[] vec; }
-
-and:

-

package points;
-public class Point {
-	protected int x, y;
-	public void move(int dx, int dy) { x += dx; y += dy; }
-	public int getX() { return x; }
-	public int getY() { return y; }
-}
-
-which declare two class types in the package points:

-

-See §6.6.7 for an example of how the protected access modifier limits access.

- -

6.6.4 Example: Access to public and Non-public Classes

- -If a class lacks the public modifier, access to the class declaration is limited to the package in which it is declared (§6.6). In the example:

-

package points;
-public class Point {
-	public int x, y;
-	public void move(int dx, int dy) { x += dx; y += dy; }
-}
-class PointList {
-	Point next, prev;
-}
-
-two classes are declared in the compilation unit. The class Point is available outside the package points, while the class PointList is available for access only within the package.

- -Thus a compilation unit in another package can access points.Point, either by using its fully qualified name: -

package pointsUser;
-class Test {
-	public static void main(String[] args) {
-		points.Point p = new points.Point();
-		System.out.println(p.x + " " + p.y);
-	}
-}
-
-or by using a single-type-import declaration (§7.5.1) that mentions the fully qualified name, so that the simple name may be used thereafter:

-

package pointsUser;
-import points.Point;
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		System.out.println(p.x + " " + p.y);
-	}
-}
-
-However, this compilation unit cannot use or import points.PointList, which is not declared public and is therefore inaccessible outside package points.

- -

6.6.5 Example: Default-Access Fields, Methods, and Constructors

- -If none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package.

- -If a public class has a method or constructor with default access, then this method or constructor is not accessible to or inherited by a subclass declared outside this package. - -

-For example, if we have: -

package points;
-public class Point {
-	public int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	public void moveAlso(int dx, int dy) { move(dx, dy); }
-}
-
-then a subclass in another package may declare an unrelated move method, with the same signature (§8.3.2) and return type. Because the original move method is not accessible from package morepoints, super may not be used:

-

package morepoints;
-public class PlusPoint extends points.Point {
-	public void move(int dx, int dy) {
-		super.move(dx, dy);								// compile-time error
-		moveAlso(dx, dy);
-	}
-}
-
-Because move of Point is not overridden by move in PlusPoint, the method moveAlso in Point never calls the method move in PlusPoint.

- -Thus if you delete the super.move call from PlusPoint and execute the test program: -

import points.Point;
-import morepoints.PlusPoint;
-class Test {
-    public static void main(String[] args) {
-        PlusPoint pp = new PlusPoint();
-        pp.move(1, 1);
-	}
-}
-
-it terminates normally. If move of Point were overridden by move in PlusPoint, then this program would recurse infinitely, until a StackoverflowError occurred.

- -

6.6.6 Example: public Fields, Methods, and Constructors

- -A public class member or constructor is accessible throughout the package where it is declared and from any other package, provided the package in which it is declared is observable (§7.4.3). For example, in the compilation unit:

-

package points;
-public class Point {
-	int x, y;
-	public void move(int dx, int dy) {
-		x += dx; y += dy;
-		moves++;
-	}
-	public static int moves = 0;
-}
-
-the public class Point has as public members the move method and the moves field. These public members are accessible to any other package that has access to package points. The fields x and y are not public and therefore are accessible only from within the package points.

- -

6.6.7 Example: protected Fields, Methods, and Constructors

- -Consider this example, where the points package declares:

-

package points;
-public class Point {
-	protected int x, y;
-	void warp(threePoint.Point3d a) {
-		if (a.z > 0)		// compile-time error: cannot access a.z
-			a.delta(this);
-	}
-}
-
-and the threePoint package declares:

-

package threePoint;
-import points.Point;
-public class Point3d extends Point {
-	protected int z;
-	public void delta(Point p) {
-		p.x += this.x;		// compile-time error: cannot access p.x
-		p.y += this.y;		// compile-time error: cannot access p.y
-	}
-	public void delta3d(Point3d q) {
-		q.x += this.x;
-		q.y += this.y;
-		q.z += this.z;
-	}
-}
-
-which defines a class Point3d. A compile-time error occurs in the method delta here: it cannot access the protected members x and y of its parameter p, because while Point3d (the class in which the references to fields x and y occur) is a subclass of Point (the class in which x and y are declared), it is not involved in the implementation of a Point (the type of the parameter p). The method delta3d can access the protected members of its parameter q, because the class Point3d is a subclass of Point and is involved in the implementation of a Point3d.

- -The method delta could try to cast (§5.5, §15.16) its parameter to be a Point3d, but this cast would fail, causing an exception, if the class of p at run time were not Point3d. - -

A compile-time error also occurs in the method warp: it cannot access the protected member z of its parameter a, because while the class Point (the class in which the reference to field z occurs) is involved in the implementation of a Point3d (the type of the parameter a), it is not a subclass of Point3d (the class in which z is declared). - -

6.6.8 Example: private Fields, Methods, and Constructors

- -A private class member or constructor is accessible only within the class body in which the member is declared and is not inherited by subclasses. In the example:

-

class Point {
-	Point() { setMasterID(); }
-	int x, y;
-	private int ID;
-	private static int masterID = 0;
-	private void setMasterID() { ID = masterID++; }
-}
-
-the private members ID, masterID, and setMasterID may be used only within the body of class Point. They may not be accessed by qualified names, field access expressions, or method invocation expressions outside the body of the declaration of Point.

- -See §8.8.8 for an example that uses a private constructor. - -

6.7 Fully Qualified Names and Canonical Names

- -Every package, top level class, top level interface, and primitive type has a fully qualified name. An array type has a fully qualified name if and only if its element type has a fully qualified name.

-

-Examples:

-

-In the example:

-

package points;
-class Point { int x, y; }
-class PointVec {
-	Point[] vec;
-}
-
-the fully qualified name of the type Point is "points.Point"; the fully qualified name of the type PointVec is "points.PointVec"; and the fully qualified name of the type of the field vec of class PointVec is "points.Point[]".

- -Every package, top level class, top level interface, and primitive type has a canonical name. An array type has a canonical name if and only if its element type has a canonical name. A member class or member interface M declared in another class C has a canonical name if and only if C has a canonical name. In that case, the canonical name of M consists of the canonical name of C, followed by ".", followed by the simple name of M. For every package, top level class, top level interface and primitive type, the canonical name is the same as the fully qualified name. The canonical name of an array type is defined only when the component type of the array has a canonical name. In that case, the canonical name of the array type consists of the canonical name of the component type of the array type followed by "[]".

- -The difference between a fully qualified name and a canonical name can be seen in examples such as: -

package p;
-class O1 { class I{}}
-class O2 extends O1{};
-
-
-In this example both p.O1.I and p.O2.I are fully qualified names that denote the same class, but only p.O1.I is its canonical name.

- -

6.8 Naming Conventions

- -The class libraries of the Java platform attempt to use, whenever possible, names chosen according to the conventions presented here. These conventions help to make code more readable and avoid certain kinds of name conflicts.

- -We recommend these conventions for use in all programs written in the Java programming language. However, these conventions should not be followed slavishly if long-held conventional usage dictates otherwise. So, for example, the sin and cos methods of the class java.lang.Math have mathematically conventional names, even though these method names flout the convention suggested here because they are short and are not verbs. - -

6.8.1 Package Names

- -Names of packages that are to be made widely available should be formed as described in §7.7. Such names are always qualified names whose first identifier consists of two or three lowercase letters that name an Internet domain, such as com, edu, gov, mil, net, org, or a two-letter ISO country code such as uk or jp. Here are examples of hypothetical unique names that might be formed under this convention:

-

com.JavaSoft.jag.Oak
-org.npr.pledge.driver
-uk.ac.city.rugby.game
-
-
-Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved by Sun for naming Java platform packages. - -

-When package names occur in expressions: -

-

6.8.2 Class and Interface Type Names

- -Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed case with the first letter of each word capitalized. For example:

-

ClassLoader
-SecurityManager
-Thread
-Dictionary
-BufferedInputStream
-
- -Likewise, names of interface types should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces java.io.DataInput and java.io.DataOutput; or it may be an adjective describing a behavior, as for the interfaces Runnable and Cloneable. - -

-Obscuring involving class and interface type names is rare. Names of fields, parameters, and local variables normally do not obscure type names because they conventionally begin with a lowercase letter whereas type names conventionally begin with an uppercase letter. - -

6.8.3 Method Names

- -Method names should be verbs or verb phrases, in mixed case, with the first letter lowercase and the first letter of any subsequent words capitalized. Here are some additional specific conventions for method names:

-

-Whenever possible and appropriate, basing the names of methods in a new class on names in an existing class that is similar, especially a class from the Java Application Programming Interface classes, will make it easier to use.

- -Method names cannot obscure or be obscured by other names (§6.5.7). - -

6.8.4 Field Names

- -Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. Note that well-designed classes have very few public or protected fields, except for fields that are constants (final static fields) (§6.8.5).

- -Fields should have names that are nouns, noun phrases, or abbreviations for nouns. Examples of this convention are the fields buf, pos, and count of the class java.io.ByteArrayInputStream and the field bytesTransferred of the class java.io.InterruptedIOException. - -

Obscuring involving field names is rare. -

-

6.8.5 Constant Names

- -The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class Character.

- -A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in: -

interface ProcessStates {
-	int PS_RUNNING = 0;
-	int PS_SUSPENDED = 1;
-}
-
-Obscuring involving constant names is rare:

-

-

6.8.6 Local Variable and Parameter Names

- -Local variable and parameter names should be short, yet meaningful. They are often short sequences of lowercase letters that are not words. For example:

-

-

One-character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type. Conventional one-character names are: - -

-Local variable or parameter names that consist of only two or three lowercase letters should not conflict with the initial country codes and domain names that are the first component of unique package names (§7.7). - -

- - -


- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - - - - Packages - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 7

- -

Packages

-

- -Programs are organized as sets of packages. Each package has its own set of names for types, which helps to prevent name conflicts. A top level type is accessible (§6.6) outside the package that declares it only if the type is declared public.

- -The naming structure for packages is hierarchical (§7.1). The members of a package are class and interface types (§7.6), which are declared in compilation units of the package, and subpackages, which may contain compilation units and subpackages of their own.

- -A package can be stored in a file system (§7.2.1) or in a database (§7.2.2). Packages that are stored in a file system have certain constraints on the organization of their compilation units to allow a simple implementation to find classes easily.

- -A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.

- -For small programs and casual development, a package can be unnamed (§7.4.2) or have a simple name, but if code is to be widely distributed, unique package names should be chosen (§7.7). This can prevent the conflicts that would otherwise occur if two development groups happened to pick the same package name and these packages were later to be used in a single program. - -

7.1 Package Members

- -The members of a package are subpackages and all the top level (§7.6) class (§8) and top level interface (§9) types declared in all the compilation units (§7.3) of the package.

- -For example, in the Java Application Programming Interface:

-

-If the fully qualified name (§6.7) of a package is P, and Q is a subpackage of P, then P.Q is the fully qualified name of the subpackage.

- -A package may not contain two members of the same name, or a compile-time error results.

- -Here are some examples: -

-The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in itself other than the prohibition against a package having a subpackage with the same simple name as a top level type (§7.6) declared in that package. There is no special access relationship between a package named oliver and another package named oliver.twist, or between packages named evelyn.wood and evelyn.waugh. For example, the code in a package named oliver.twist has no better access to the types declared within package oliver than code in any other package. - -

7.2 Host Support for Packages

- -Each host determines how packages, compilation units, and subpackages are created and stored, and which compilation units are observable (§7.3) in a particular compilation.

- -The observability of compilation units in turn determines which packages are observable, and which packages are in scope. - -

The packages may be stored in a local file system in simple implementations of the Java platform. Other implementations may use a distributed file system or some form of database to store source and/or binary code. - -

7.2.1 Storing Packages in a File System

- -As an extremely simple example, all the packages and source and binary code on a system might be stored in a single directory and its subdirectories. Each immediate subdirectory of this directory would represent a top level package, that is, one whose fully qualified name consists of a single simple name. The directory might contain the following immediate subdirectories:

-

com
-gls
-jag
-java
-wnj
-
-where directory java would contain the Java Application Programming Interface packages; the directories jag, gls, and wnj might contain packages that three of the authors of this specification created for their personal use and to share with each other within this small group; and the directory com would contain packages procured from companies that used the conventions described in §7.7 to generate unique names for their packages.

- -Continuing the example, the directory java would contain, among others, the following subdirectories: -

applet	
-awt
-io
-lang
-net
-util
-
-corresponding to the packages java.applet, java.awt, java.io, java.lang, java.net, and java.util that are defined as part of the Java Application Programming Interface.

- -Still continuing the example, if we were to look inside the directory util, we might see the following files: -

-BitSet.java				Observable.java
-BitSet.class				Observable.class
-Date.java				Observer.java
-Date.class				Observer.class
-...
-
-where each of the .java files contains the source for a compilation unit (§7.3) that contains the definition of a class or interface whose binary compiled form is contained in the corresponding .class file.

- -Under this simple organization of packages, an implementation of the Java platform would transform a package name into a pathname by concatenating the components of the package name, placing a file name separator (directory indicator) between adjacent components. - -

For example, if this simple organization were used on a UNIX system, where the file name separator is /, the package name: -

jag.scrabble.board
-
-would be transformed into the directory name:

-

jag/scrabble/board
-
-and:

-

com.sun.sunsoft.DOE
-
-would be transformed to the directory name:

-

com/sun/sunsoft/DOE
-
-
-A package name component or class name might contain a character that cannot correctly appear in a host file system's ordinary directory name, such as a Unicode character on a system that allows only ASCII characters in file names. As a convention, the character can be escaped by using, say, the @ character followed by four hexadecimal digits giving the numeric value of the character, as in the \uxxxx escape (§3.3), so that the package name: -
-children.activities.crafts.papierM\u00e2ch\u00e9
-
-which can also be written using full Unicode as:

-

children.activities.crafts.papierMâché
-
-might be mapped to the directory name:

-

children/activities/crafts/papierM@00e2ch@00e9
-
-If the @ character is not a valid character in a file name for some given host file system, then some other character that is not valid in an identifier could be used instead.

- -

7.2.2 Storing Packages in a Database

- -A host system may store packages and their compilation units and subpackages in a database.

- -Such a database must not impose the optional restrictions (§7.6) on compilation units in file-based implementations. For example, a system that uses a database to store packages may not enforce a maximum of one public class or interface per compilation unit. - -

-Systems that use a database must, however, provide an option to convert a program to a form that obeys the restrictions, for purposes of export to file-based implementations.

- -

7.3 Compilation Units

- -CompilationUnit is the goal symbol (§2.1) for the syntactic grammar (§2.3) of Java programs. It is defined by the following productions:

-

-Types declared in different compilation units can depend on each other, circularly. A Java compiler must arrange to compile all such types at the same time.

- -A compilation unit consists of three parts, each of which is optional:

-

-Which compilation units are observable is determined by the host system. However, all the compilation units of the package java and its subpackages lang and io must always be observable. The observability of a compilation unit influences the observability of its package (§7.4.3).

- -Every compilation unit automatically and implicitly imports every public type name declared by the predefined package java.lang, so that the names of all those types are available as simple names, as described in §7.5.3.

- -

7.4 Package Declarations

- -A package declaration appears within a compilation unit to indicate the package to which the compilation unit belongs.

- -

7.4.1 Named Packages

- -A package declaration in a compilation unit specifies the name (§6.2) of the package to which the compilation unit belongs.

-

-The package name mentioned in a package declaration must be the fully qualified name (§6.7) of the package.

- -

7.4.2 Unnamed Packages

- -A compilation unit that has no package declaration is part of an unnamed package.

- -Note that an unnamed package cannot have subpackages, since the syntax of a package declaration always includes a reference to a named top level package. -

- -As an example, the compilation unit:

-

class FirstCall {
-	public static void main(String[] args) {
-		System.out.println("Mr. Watson, come here. "
-						+ "I want you.");
-	}
-}
-
-defines a very simple compilation unit as part of an unnamed package.

- -An implementation of the Java platform must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.

- -In implementations of the Java platform that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is observable at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system. - -

-Unnamed packages are provided by the Java platform principally for convenience when developing small or temporary applications or when just beginning development. - -

7.4.3 Observability of a Package

- -A package is observable if and only if either:

-

-One can conclude from the rule above and from the requirements on observable compilation units, that the packages java, java.lang, and java.io are always observable. - -

7.4.4 Scope of a Package Declaration

- -The scope of the declaration of an observable (§7.4.3) top level package is all observable compilation units (§7.3). The declaration of a package that is not observable is never in scope. Subpackage declarations are never in scope.

- -It follows that the package java is always in scope (§6.3). -

- -Package declarations never shadow other declarations.

- -

7.5 Import Declarations

- -An import declaration allows a named type to be referred to by a simple name (§6.2) that consists of a single identifier. Without the use of an appropriate import declaration, the only way to refer to a type declared in another package is to use a fully qualified name (§6.7).

-

-A single-type-import declaration (§7.5.1) imports a single named type, by mentioning its canonical name. A type-import-on-demand declaration (§7.5.2) imports all the accessible types of a named type or package as needed.

- -The scope of a type imported by a single-type-import declaration (§7.5.1) or type-import-on-demand declaration (§7.5.2) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.

- -An import declaration makes types available by their simple names only within the compilation unit that actually contains the import declaration. The scope of the entities(s) it introduces specifically does not include the package statement, other import declarations in the current compilation unit, or other compilation units in the same package. See §7.5.4 for an illustrative example.

- -

7.5.1 Single-Type-Import Declaration

- -A single-type-import declaration imports a single type by giving its canonical name, making it available under a simple name in the class and interface declarations of the compilation unit in which the single-type import declaration appears.

-

-The TypeName must be the canonical name of a class or interface type; a compile-time error occurs if the named type does not exist. The named type must be accessible (§6.6) or a compile-time error occurs.

- -A single-type-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

-

-throughout c.

- -The example: -

import java.util.Vector;
-
-causes the simple name Vector to be available within the class and interface declarations in a compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places where it is not shadowed (§6.3.1) or obscured (§6.3.2) by a declaration of a field, parameter, local variable, or nested type declaration with the same name.

- -If two single-type-import declarations in the same compilation unit attempt to import types with the same simple name, then a compile-time error occurs, unless the two types are the same type, in which case the duplicate declaration is ignored. If another top level type with the same simple name is otherwise declared in the current compilation unit except by a type-import-on-demand declaration (§7.5.2), then a compile-time error occurs.

- -So the sample program: -

import java.util.Vector;
-class Vector { Object[] vec; }
-
-causes a compile-time error because of the duplicate declaration of Vector, as does:

-

import java.util.Vector;
-import myVector.Vector;
-
-where myVector is a package containing the compilation unit:

-

package myVector;
-public class Vector { Object[] vec; }
-
-The compiler keeps track of types by their binary names (§13.1).

- -Note that an import statement cannot import a subpackage, only a type. For example, it does not work to try to import java.util and then use the name util.Random to refer to the type java.util.Random: -

-import java.util;		// incorrect: compile-time error
-class Test { util.Random generator; }
-
-

7.5.2 Type-Import-on-Demand Declaration

- -A type-import-on-demand declaration allows all accessible (§6.6) types declared in the type or package named by a canonical name to be imported as needed.

-

-It is a compile-time error for a type-import-on-demand declaration to name a type or package that is not accessible. Two or more type-import-on-demand declarations in the same compilation unit may name the same type or package; the effect is as if there were exactly one such declaration. It is not a compile-time error to name the current package or java.lang in a type-import-on-demand declaration. The type-import-on-demand declaration is ignored in such cases

- -A type-import-on-demand declaration never causes any other declaration to be shadowed.

- -The example:

-

import java.util.*;
-
-causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places in the compilation unit where that type declaration is not shadowed (§6.3.1) or obscured (§6.3.2). The declaration might be shadowed by a single-type-import declaration of a type whose simple name is Vector; by a type named Vector and declared in the package to which the compilation unit belongs; or any nested classes or interfaces. The declaration might be obscured by a declaration of a field, parameter, or local variable named Vector (It would be unusual for any of these conditions to occur.)

- -

7.5.3 Automatic Imports

- -Each compilation unit automatically imports all of the public type names declared in the predefined package java.lang, as if the declaration:

-

import java.lang.*;
-
-appeared at the beginning of each compilation unit, immediately following any package statement.

- -

7.5.4 A Strange Example

- -Package names and type names are usually different under the naming conventions described in §6.8. Nevertheless, in a contrived example where there is an unconventionally-named package Vector, which declares a public class named Mosquito:

-

package Vector;
-public class Mosquito { int capacity; }
-
-and then the compilation unit:

-

package strange.example;
-import java.util.Vector;
-import Vector.Mosquito;
-class Test {
-	public static void main(String[] args) {
-		System.out.println(new Vector().getClass());
-		System.out.println(new Mosquito().getClass());
-	}
-}
-
-the single-type-import declaration (§7.5.1) importing class Vector from package java.util does not prevent the package name Vector from appearing and being correctly recognized in subsequent import declarations. The example compiles and produces the output:

-

class java.util.Vector
-class Vector.Mosquito
-
-

7.6 Top Level Type Declarations

- -A top level type declaration declares a top level class type (§8) or a top level interface type (§9):

-

-By default, the top level types declared in a package are accessible only within the compilation units of that package, but a type may be declared to be public to grant access to the type from code in other packages (§6.6, §8.1.1, §9.1.1).

- -The scope of a top level type is all type declarations in the package in which the top level type is declared.

- -If a top level type named T is declared in a compilation unit of a package whose fully qualified name is P, then the fully qualified name of the type is P.T. If the type is declared in an unnamed package (§7.4.2), then the type has the fully qualified name T.

- -Thus in the example:

-

package wnj.points;
-class Point { int x, y; }
-
-the fully qualified name of class Point is wnj.points.Point.

- -An implementation of the Java platform must keep track of types within packages by their binary names (§13.1). Multiple ways of naming a type must be expanded to binary names to make sure that such names are understood as referring to the same type.

- -For example, if a compilation unit contains the single-type-import declaration (§7.5.1): -

import java.util.Vector;
-
-then within that compilation unit the simple name Vector and the fully qualified name java.util.Vector refer to the same type.

- -When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

-

-This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

- -When packages are stored in a database (§7.2.2), the host system must not impose such restrictions.

- -In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units. - -A compile-time error occurs if the name of a top level type appears as the name of any other top level class or interface type declared in the same package (§7.6).

- -A compile-time error occurs if the name of a top level type is also declared as a type by a single-type-import declaration (§7.5.1) in the compilation unit (§7.3) containing the type declaration.

- -In the example: -

class Point { int x, y; }
-
-the class Point is declared in a compilation unit with no package statement, and thus Point is its fully qualified name, whereas in the example:

-

package vista;
-class Point { int x, y; }
-
-the fully qualified name of the class Point is vista.Point. (The package name vista is suitable for local or personal use; if the package were intended to be widely distributed, it would be better to give it a unique package name (§7.7).)

- -In the example: -

package test;
-import java.util.Vector;
-class Point {
-	int x, y;
-}
-interface Point {			// compile-time error #1
-	int getR();
-	int getTheta();
-}
-class Vector { Point[] pts; }		// compile-time error #2
-
-the first compile-time error is caused by the duplicate declaration of the name Point as both a class and an interface in the same package. A second error detected at compile time is the attempt to declare the name Vector both by a class type declaration and by a single-type-import declaration.

- -Note, however, that it is not an error for the name of a class to also to name a type that otherwise might be imported by a type-import-on-demand declaration (§7.5.2) in the compilation unit (§7.3) containing the class declaration. In the example: -

package test;
-import java.util.*;
-class Vector { Point[] pts; }		// not a compile-time error
-
-the declaration of the class Vector is permitted even though there is also a class java.util.Vector. Within this compilation unit, the simple name Vector refers to the class test.Vector, not to java.util.Vector (which can still be referred to by code within the compilation unit, but only by its fully qualified name).

- -As another example, the compilation unit: -

package points;
-class Point {
-	int x, y;			// coordinates
-	PointColor color;		// color of this point
-	Point next;			// next point with this color
-	static int nPoints;
-}
-class PointColor {
-	Point first;			// first point with this color
-	PointColor(int color) {
-		this.color = color;
-	}
-	private int color;		// color components
-}
-
-defines two classes that use each other in the declarations of their class members. Because the class types Point and PointColor have all the type declarations in package points, including all those in the current compilation unit, as their scope, this example compiles correctly-that is, forward reference is not a problem.

- -It is a compile-time error if a top level type declaration contains any one of the following access modifiers: protected, private or static.

- -

7.7 Unique Package Names

- -Developers should take steps to avoid the possibility of two published packages having the same name by choosing unique package names for packages that are widely distributed. This allows packages to be easily and automatically installed and catalogued. This section specifies a suggested convention for generating such unique package names. Implementations of the Java platform are encouraged to provide automatic support for converting a set of packages from local and casual package names to the unique name format described here.

- -If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create a situation that is difficult or impossible for the user or programmer to resolve. The class ClassLoader can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a naïve program. - -

You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as sun.com. You then reverse this name, component by component, to obtain, in this example, com.sun, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names. - -

In some cases, the internet domain name may not be a valid package name. Here are some suggested conventions for dealing with these situations: -

-Such a convention might specify that certain directory name components be division, department, project, machine, or login names. Some possible examples: -
com.sun.sunsoft.DOE
-com.sun.java.jag.scrabble
-com.apple.quicktime.v2
-edu.cmu.cs.bovik.cheese
-gov.whitehouse.socks.mousefinder
-
-The first component of a unique package name is always written in all-lowercase ASCII letters and should be one of the top level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. For more information, refer to the documents stored at ftp://rs.internic.net/rfc, for example, rfc920.txt and rfc1032.txt.

- -The name of a package is not meant to imply where the package is stored within the Internet; for example, a package named edu.cmu.cs.bovik.cheese is not necessarily obtainable from Internet address cmu.edu or from cs.cmu.edu or from bovik.cs.cmu.edu. The suggested convention for generating unique package names is merely a way to piggyback a package naming convention on top of an existing, widely known unique name registry instead of having to create a separate registry for package names. - -

- - -


- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - - - - Classes - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 8

- -

Classes

-

- -Class declarations define new reference types and describe how they are implemented (§8.1).

- -A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.

- -This chapter discusses the common semantics of all classes-top level (§7.6) and nested (including member classes (§8.5, §9.5), local classes (§14.3) and anonymous classes (§15.9.5)). Details that are specific to particular kinds of classes are discussed in the sections dedicated to these constructs.

- -A named class may be declared abstract (§8.1.1.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. A class may be declared final (§8.1.1.2), in which case it cannot have subclasses. If a class is declared public, then it can be referred to from other packages.

- -Each class except Object is an extension of (that is, a subclass of) a single existing class (§8.1.3) and may implement interfaces (§8.1.4). - -

-The body of a class declares members (fields and methods and nested classes and interfaces), instance and static initializers, and constructors (§8.1.5). The scope (§6.3) of a member (§8.2) is the entire declaration of the class to which the member belongs. Field, method, member class, member interface, and constructor declarations may include the access modifiers (§6.6) public, protected, or private. The members of a class include both declared and inherited members (§8.2). Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared class members and interface members can hide class or interface members declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.

- -Field declarations (§8.3) describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared final (§8.3.1.2), in which case it can be assigned to only once. Any field declaration may include an initializer.

- -Member class declarations (§8.5) describe nested classes that are members of the surrounding class. Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (§8.1.2).

- -Member interface declarations (§8.5) describe nested interfaces that are members of the surrounding class.

- -Method declarations (§8.4) describe code that may be invoked by method invocation expressions (§15.12). A class method is invoked relative to the class type; an instance method is invoked with respect to some particular object that is an instance of the class type. A method whose declaration does not indicate how it is implemented must be declared abstract. A method may be declared final (§8.4.3.3), in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent native code (§8.4.3.4). A synchronized method (§8.4.3.6) automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a synchronized statement (§14.18), thus allowing its activities to be synchronized with those of other threads (§17).

- -Method names may be overloaded (§8.4.7).

- -Instance initializers (§8.6) are blocks of executable code that may be used to help initialize an instance when it is created (§15.9).

- -Static initializers (§8.7) are blocks of executable code that may be used to help initialize a class when it is first loaded (§12.4).

- -Constructors (§8.8) are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded (§8.8.6).

- -

8.1 Class Declaration

- -A class declaration specifies a new named reference type:

-

-The Identifier in a class declaration specifies the name of the class. A compile-time error occurs if a class has the same simple name as any of its enclosing classes or interfaces.

- -

8.1.1 Class Modifiers

- -A class declaration may include class modifiers.

-

-Not all modifiers are applicable to all kinds of class declarations. The access modifier public pertains only to top level classes (§7.6) and to member classes (§8.5, §9.5), and is discussed in §6.6, §8.5 and §9.5. The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration (§8.5) and are discussed in §8.5.1. The access modifier static pertains only to member classes (§8.5, §9.5). A compile-time error occurs if the same modifier appears more than once in a class declaration.

- -If two or more class modifiers appear in a class declaration, then it is customary, though not required, that they appear in the order consistent with that shown above in the production for ClassModifier.

- -

8.1.1.1 abstract Classes

- -An abstract class is a class that is incomplete, or to be considered incomplete. Only abstract classes may have abstract methods (§8.4.3.1, §9.4), that is, methods that are declared but not yet implemented. If a class that is not abstract contains an abstract method, then a compile-time error occurs. A class C has abstract methods if any of the following is true:

-

-In the example: -
abstract class Point {
-	int x = 1, y = 1;
-	void move(int dx, int dy) {
-		x += dx;
-		y += dy;
-		alert();
-	}
-	abstract void alert();
-}
-abstract class ColoredPoint extends Point {
-	int color;
-}
-class SimplePoint extends Point {
-	void alert() { }
-}
-
-a class Point is declared that must be declared abstract, because it contains a declaration of an abstract method named alert. The subclass of Point named ColoredPoint inherits the abstract method alert, so it must also be declared abstract. On the other hand, the subclass of Point named SimplePoint provides an implementation of alert, so it need not be abstract.

- -A compile-time error occurs if an attempt is made to create an instance of an abstract class using a class instance creation expression (§15.9).

- -Thus, continuing the example just shown, the statement: -

	Point p = new Point();
-
-would result in a compile-time error; the class Point cannot be instantiated because it is abstract. However, a Point variable could correctly be initialized with a reference to any subclass of Point, and the class SimplePoint is not abstract, so the statement:

-

	Point p = new SimplePoint();
-
-would be correct.

- -A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class. Thus, in the example just given, instantiation of a SimplePoint causes the default constructor and field initializers for x and y of Point to be executed. - -It is a compile-time error to declare an abstract class type such that it is not possible to create a subclass that implements all of its abstract methods. This situation can occur if the class would have as members two abstract methods that have the same method signature (§8.4.2) but different return types.

- -As an example, the declarations: -

interface Colorable { void setColor(int color); }
-abstract class Colored implements Colorable {
-	abstract int setColor(int color);
-}
-
-result in a compile-time error: it would be impossible for any subclass of class Colored to provide an implementation of a method named setColor, taking one argument of type int, that can satisfy both abstract method specifications, because the one in interface Colorable requires the same method to return no value, while the one in class Colored requires the same method to return a value of type int (§8.4).

- -A class type should be declared abstract only if the intent is that subclasses can be created to complete the implementation. If the intent is simply to prevent instantiation of a class, the proper way to express this is to declare a constructor (§8.8.8) of no arguments, make it private, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables. The class Math is an example of a class that cannot be instantiated; its declaration looks like this: -

public final class Math {
-	private Math() { }		// never instantiate this class
-	. . . declarations of class variables and methods . . .
-
-}
-
-

8.1.1.2 final Classes

- -A class can be declared final if its definition is complete and no subclasses are desired or required. A compile-time error occurs if the name of a final class appears in the extends clause (§8.1.3) of another class declaration; this implies that a final class cannot have any subclasses. A compile-time error occurs if a class is declared both final and abstract, because the implementation of such a class could never be completed (§8.1.1.1).

- -Because a final class never has any subclasses, the methods of a final class are never overridden (§8.4.6.1). - -

8.1.1.3 strictfp Classes

- -The effect of the strictfp modifier is to make all float or double expressions within the class declaration be explicitly FP-strict (§15.4). This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp.

- -Note also that all float or double expressions within all variable initializers, instance initializers, static initializers and constructors of the class will also be explicitly FP-strict. - -

8.1.2 Inner Classes and Enclosing Instances

- -An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

- -To illustrate these rules, consider the example below: -

class HasStatic{
-	static int j = 100;
-}
-class Outer{
-	class Inner extends HasStatic{
-		static final x = 3;		// ok - compile-time constant
-		static int y = 4; 		// compile-time error, an inner class
-	}
-	static class NestedButNotInner{
-		static int z = 5; 		// ok, not an inner class
-	}
-	interface NeverInner{}		// interfaces are never inner
-}
-
-Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Member interfaces (§8.5) are always implicitly static so they are never considered to be inner classes.

- -A statement or expression occurs in a static context if and only if the innermost method, constructor, instance initializer, static initializer, field initializer, or explicit constructor statement enclosing the statement or expression is a static method, a static initializer, the variable initializer of a static variable, or an explicit constructor invocation statement (§8.8.5).

- -An inner class C is a direct inner class of a class O if O is the immediately lexically enclosing class of C and the declaration of C does not occur in a static context. A class C is an inner class of class O if it is either a direct inner class of O or an inner class of an inner class of O.

- -A class O is the zeroth lexically enclosing class of itself. A class O is the nth lexically enclosing class of a class C if it is the immediately enclosing class of the n - 1st lexically enclosing class of C.

- -An instance i of a direct inner class C of a class O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (§15.9.2).

- -An object o is the zeroth lexically enclosing instance of itself. An object o is the nth lexically enclosing instance of an instance i if it is the immediately enclosing instance of the n - 1st lexically enclosing instance of i.

- -When an inner class refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used. A blank final (§4.5.4) field of a lexically enclosing class may not be assigned within an inner class.

- -An instance of an inner class I whose declaration occurs in a static context has no lexically enclosing instances. However, if I is immediately declared within a static method or static initializer then I does have an enclosing block, which is the innermost block statement lexically enclosing the declaration of I.

- -Furthermore, for every superclass S of C which is itself a direct inner class of a class SO, there is an instance of SO associated with i, known as the immediately enclosing instance of i with respect to S. The immediately enclosing instance of an object with respect to its class' direct superclass, if any, is determined when the superclass constructor is invoked via an explicit constructor invocation statement.

- -Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final, and must be definitely assigned (§16) before the body of the inner class.

- -Inner classes include local (§14.3), anonymous (§15.9.5) and non-static member classes (§8.5). Here are some examples: -

class Outer {
-	int i = 100;
-	static void classMethod() {
-		final int l = 200;
-		class LocalInStaticContext{
-			int k = i; // compile-time error
-			int m = l; // ok
-		}
-	}
-	void foo() {
-		class Local { // a local class
-			int j = i;
-		}
-	}
-}
-
- -The declaration of class LocalInStaticContext occurs in a static context-within the static method classMethod. Instance variables of class Outer are not available within the body of a static method. In particular, instance variables of Outer are not available inside the body of LocalInStaticContext. However, local variables from the surrounding method may be referred to without error (provided they are marked final). - -

Inner classes whose declarations do not occur in a static context may freely refer to the instance variables of their enclosing class. An instance variable is always defined with respect to an instance. In the case of instance variables of an enclosing class, the instance variable must be defined with respect to an enclosing instance of that class. So, for example, the class Local above has an enclosing instance of class Outer. As a further example: -

-class WithDeepNesting{
-	boolean toBe;
-	WithDeepNesting(boolean b) { toBe = b;}
-	class Nested {
-		boolean theQuestion;
-		class DeeplyNested {
-			DeeplyNested(){
-				theQuestion = toBe || !toBe;
-			}
-		}
-	}
-}
-
-Here, every instance of WithDeepNesting.Nested.DeeplyNested has an enclosing instance of class WithDeepNesting.Nested (its immediately enclosing instance) and an enclosing instance of class WithDeepNesting (its 2nd lexically enclosing instance).

- -

8.1.3 Superclasses and Subclasses

- -The optional extends clause in a class declaration specifies the direct superclass of the current class. A class is said to be a direct subclass of the class it extends. The direct superclass is the class from whose implementation the implementation of the current class is derived. The extends clause must not appear in the definition of the class Object, because it is the primordial class and has no direct superclass. If the class declaration for any other class has no extends clause, then the class has the class Object as its implicit direct superclass.

-

-The following is repeated from §4.3 to make the presentation here clearer:

-

-The ClassType must name an accessible (§6.6) class type, or a compile-time error occurs. If the specified ClassType names a class that is final (§8.1.1.2), then a compile-time error occurs; final classes are not allowed to have subclasses.

- -In the example: -

class Point { int x, y; }
-final class ColoredPoint extends Point { int color; }
-class Colored3DPoint extends ColoredPoint { int z; } // error
-
-the relationships are as follows:

-

-The declaration of class Colored3dPoint causes a compile-time error because it attempts to extend the final class ColoredPoint.

- -The subclass relationship is the transitive closure of the direct subclass relationship. A class A is a subclass of class C if either of the following is true:

-

-Class C is said to be a superclass of class A whenever A is a subclass of C.

- -In the example: -

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-final class Colored3dPoint extends ColoredPoint { int z; }
-
-the relationships are as follows:

-

-A class C directly depends on a type T if T is mentioned in the extends or implements clause of C either as a superclass or superinterface, or as a qualifier within a superclass or superinterface name. A class C depends on a reference type T if any of the following conditions hold:

-

-It is a compile-time error if a class depends on itself.

- -For example: -

class Point extends ColoredPoint { int x, y; }
-class ColoredPoint extends Point { int color; }
-
-causes a compile-time error.

- -If circularly declared classes are detected at run time, as classes are loaded (§12.2), then a ClassCircularityError is thrown.

- -

8.1.4 Superinterfaces

- -The optional implements clause in a class declaration lists the names of interfaces that are direct superinterfaces of the class being declared:

-

-The following is repeated from §4.3 to make the presentation here clearer:

-

-Each InterfaceType must name an accessible (§6.6) interface type, or a compile-time error occurs.

- -A compile-time error occurs if the same interface is mentioned two or more times in a single implements clause.

- -This is true even if the interface is named in different ways; for example, the code: -

class Redundant implements java.lang.Cloneable, Cloneable {
-	int x;
-}
-
-results in a compile-time error because the names java.lang.Cloneable and Cloneable refer to the same interface.

- -An interface type I is a superinterface of class type C if any of the following is true:

-

-A class is said to implement all its superinterfaces.

- -In the example: -

public interface Colorable {
-	void setColor(int color);
-	int getColor();
-}
-public interface Paintable extends Colorable {
-	int MATTE = 0, GLOSSY = 1;
-	void setFinish(int finish);
-	int getFinish();
-}
-class Point { int x, y; }
-class ColoredPoint extends Point implements Colorable {
-	int color;
-	public void setColor(int color) { this.color = color; }
-	public int getColor() { return color; }
-}
-class PaintedPoint extends ColoredPoint implements Paintable 
-{
-	int finish;
-	public void setFinish(int finish) {
-		this.finish = finish;
-	}
-	public int getFinish() { return finish; }
-}
-
-the relationships are as follows:

-

-A class can have a superinterface in more than one way. In this example, the class PaintedPoint has Colorable as a superinterface both because it is a superinterface of ColoredPoint and because it is a superinterface of Paintable.

- -Unless the class being declared is abstract, the declarations of all the method members of each direct superinterface must be implemented either by a declaration in this class or by an existing method declaration inherited from the direct superclass, because a class that is not abstract is not permitted to have abstract methods (§8.1.1.1).

- -Thus, the example: -

interface Colorable {
-	void setColor(int color);
-	int getColor();
-}
-class Point { int x, y; };
-class ColoredPoint extends Point implements Colorable {
-	int color;
-}
-
-causes a compile-time error, because ColoredPoint is not an abstract class but it fails to provide an implementation of methods setColor and getColor of the interface Colorable.

- -It is permitted for a single method declaration in a class to implement methods of more than one superinterface. For example, in the code: -

interface Fish { int getNumberOfScales(); }
-interface Piano { int getNumberOfScales(); }
-class Tuna implements Fish, Piano {
-	// You can tune a piano, but can you tuna fish?
-	int getNumberOfScales() { return 91; }
-}
-
-the method getNumberOfScales in class Tuna has a name, signature, and return type that matches the method declared in interface Fish and also matches the method declared in interface Piano; it is considered to implement both.

- -On the other hand, in a situation such as this: -

interface Fish { int getNumberOfScales(); }
-interface StringBass { double getNumberOfScales(); }
-class Bass implements Fish, StringBass {
-	// This declaration cannot be correct, no matter what type is used.
-	public ??? getNumberOfScales() { return 91; }
-}
-
-It is impossible to declare a method named getNumberOfScales with the same signature and return type as those of both the methods declared in interface Fish and in interface StringBass, because a class can have only one method with a given signature (§8.4). Therefore, it is impossible for a single class to implement both interface Fish and interface StringBass (§8.4.6).

- -

8.1.5 Class Body and Member Declarations

- -A class body may contain declarations of members of the class, that is, fields (§8.3), classes (§8.5), interfaces (§8.5) and methods (§8.4). A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.

-

-The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, including any nested type declarations.

- -If C itself is a nested class, there may be definitions of the same kind (variable, method, or type) for m in enclosing scopes. (The scopes may be blocks, classes, or packages.) In all such cases, the member m declared or inherited in C shadows (§6.3.1) the other definitions of m.

- -

8.2 Class Members

- -The members of a class type are all of the following:

-

-Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

- -Constructors, static initializers, and instance initializers are not members and therefore are not inherited.

- -The example: -

class Point {
-	int x, y;
-	private Point() { reset(); }
-	Point(int x, int y) { this.x = x; this.y = y; }
-	private void reset() { this.x = 0; this.y = 0; }
-}
-class ColoredPoint extends Point {
-	int color;
-	void clear() { reset(); }		// error
-}
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint c = new ColoredPoint(0, 0);	// error
-		c.reset();				// error
-	}
-}
-
-causes four compile-time errors:

-

	ColoredPoint() { super(); }
-
- -which invokes the constructor, with no arguments, for the direct superclass of the class ColoredPoint. The error is that the constructor for Point that takes no arguments is private, and therefore is not accessible outside the class Point, even through a superclass constructor invocation (§8.8.5). - -Two more errors occur because the method reset of class Point is private, and therefore is not inherited by class ColoredPoint. The method invocations in method clear of class ColoredPoint and in method main of class Test are therefore not correct.

- -

8.2.1 Examples of Inheritance

- -This section illustrates inheritance of class members through several examples.

- -

8.2.1.1 Example: Inheritance with Default Access

- -Consider the example where the points package declares two compilation units:

-

package points;
-public class Point {
-	int x, y;
-	public void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-and:

-

package points;
-public class Point3d extends Point {
-	int z;
-	public void move(int dx, int dy, int dz) {
-		x += dx; y += dy; z += dz;
-	}
-}
-
-and a third compilation unit, in another package, is:

-

import points.Point3d;
-class Point4d extends Point3d {
-	int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		x += dx; y += dy; z += dz; w += dw; // compile-time errors
-	}
-}
-
-Here both classes in the points package compile. The class Point3d inherits the fields x and y of class Point, because it is in the same package as Point. The class Point4d, which is in a different package, does not inherit the fields x and y of class Point or the field z of class Point3d, and so fails to compile.

- -A better way to write the third compilation unit would be: -

import points.Point3d;
-class Point4d extends Point3d {
-	int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		super.move(dx, dy, dz); w += dw;
-	}
-}
-
-using the move method of the superclass Point3d to process dx, dy, and dz. If Point4d is written in this way it will compile without errors.

- -

8.2.1.2 Inheritance with public and protected

- -Given the class Point:

-

package points;
-public class Point {
-	public int x, y;
-	protected int useCount = 0;
-	static protected int totalUseCount = 0;
-	public void move(int dx, int dy) {
-		x += dx; y += dy; useCount++; totalUseCount++;
-	}
-}
-
-the public and protected fields x, y, useCount and totalUseCount are inherited in all subclasses of Point.

- -Therefore, this test program, in another package, can be compiled successfully: -

class Test extends points.Point {
-	public void moveBack(int dx, int dy) {
-		x -= dx; y -= dy; useCount++; totalUseCount++;
-	}
-}
-
-

8.2.1.3 Inheritance with private

- -In the example:

-

class Point {
-	int x, y;
-	void move(int dx, int dy) {
-		x += dx; y += dy; totalMoves++;
-	}
-	private static int totalMoves;
-	void printMoves() { System.out.println(totalMoves); }
-}
-class Point3d extends Point {
-	int z;
-	void move(int dx, int dy, int dz) {
-		super.move(dx, dy); z += dz; totalMoves++;
-	}
-}
-
-the class variable totalMoves can be used only within the class Point; it is not inherited by the subclass Point3d. A compile-time error occurs because method move of class Point3d tries to increment totalMoves.

- -

8.2.1.4 Accessing Members of Inaccessible Classes

- -Even though a class might not be declared public, instances of the class might be available at run time to code outside the package in which it is declared if it has a public superclass or superinterface. An instance of the class can be assigned to a variable of such a public type. An invocation of a public method of the object referred to by such a variable may invoke a method of the class if it implements or overrides a method of the public superclass or superinterface. (In this situation, the method is necessarily declared public, even though it is declared in a class that is not public.)

- -Consider the compilation unit: -

package points;
-public class Point {
-	public int x, y;
-	public void move(int dx, int dy) {
-		x += dx; y += dy;
-	}
-}
-
-and another compilation unit of another package:

-

package morePoints;
-class Point3d extends points.Point {
-	public int z;
-	public void move(int dx, int dy, int dz) {
-		super.move(dx, dy); z += dz;
-	}
-	public void move(int dx, int dy) {
-		move(dx, dy, 0);
-	}
-}
-public class OnePoint {
-	public static points.Point getOne() { 
-		return new Point3d(); 
-	}
-}
-
-An invocation morePoints.OnePoint.getOne() in yet a third package would return a Point3d that can be used as a Point, even though the type Point3d is not available outside the package morePoints. The two argument version of method move could then be invoked for that object, which is permissible because method move of Point3d is public (as it must be, for any method that overrides a public method must itself be public, precisely so that situations such as this will work out correctly). The fields x and y of that object could also be accessed from such a third package.

- -While the field z of class Point3d is public, it is not possible to access this field from code outside the package morePoints, given only a reference to an instance of class Point3d in a variable p of type Point. This is because the expression p.z is not correct, as p has type Point and class Point has no field named z; also, the expression ((Point3d)p).z is not correct, because the class type Point3d cannot be referred to outside package morePoints. - -

The declaration of the field z as public is not useless, however. If there were to be, in package morePoints, a public subclass Point4d of the class Point3d: -

package morePoints;
-public class Point4d extends Point3d {
-	public int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		super.move(dx, dy, dz); w += dw;
-	}
-}
-
-then class Point4d would inherit the field z, which, being public, could then be accessed by code in packages other than morePoints, through variables and expressions of the public type Point4d.

- -

8.3 Field Declarations

- -The variables of a class type are introduced by field declarations:

-

-The FieldModifiers are described in §8.3.1. The Identifier in a FieldDeclarator may be used in a name to refer to the field. Fields are members; the scope (§6.3) of a field declaration is specified in §8.1.5. More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration. Variable declarations involving array types are discussed in §10.2.

- -It is a compile-time error for the body of a class declaration to declare two fields with the same name. Methods, types, and fields may have the same name, since they are used in different contexts and are disambiguated by different lookup procedures (§6.5).

- -If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class. The field declaration also shadows (§6.3.1) declarations of any accessible fields in enclosing classes or interfaces, and any local variables, formal method parameters, and exception handler parameters with the same name in any enclosing blocks.

- -If a field declaration hides the declaration of another field, the two fields need not have the same type.

- -A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

- -Note that a private field of a superclass might be accessible to a subclass (for example, if both classes are members of the same class). Nevertheless, a private field is never inherited by a subclass. - -

It is possible for a class to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous. - -

There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity. - -

A hidden field can be accessed by using a qualified name (if it is static) or by using a field access expression (§15.11) that contains the keyword super or a cast to a superclass type. See §15.11.2 for discussion and an example. - -

A value stored in a field of type float is always an element of the float value set (§4.2.3); similarly, a value stored in a field of type double is always an element of the double value set. It is not permitted for a field of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a field of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set. - -

8.3.1 Field Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a field declaration, or if a field declaration has more than one of the access modifiers public, protected, and private.

- -If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier. - -

8.3.1.1 static Fields

- -If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

- -A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses. The example program:

-

class Point {
-	int x, y, useCount;
-	Point(int x, int y) { this.x = x; this.y = y; }
-	final static Point origin = new Point(0, 0);
-}
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point(1,1);
-		Point q = new Point(2,2);
-		p.x = 3; p.y = 3; p.useCount++; p.origin.useCount++;
-		System.out.println("(" + q.x + "," + q.y + ")");
-		System.out.println(q.useCount);
-		System.out.println(q.origin == Point.origin);
-		System.out.println(q.origin.useCount);
-	}
-}
-
-prints:

-

(2,2)
-0
-true
-1
-
-showing that changing the fields x, y, and useCount of p does not affect the fields of q, because these fields are instance variables in distinct objects. In this example, the class variable origin of the class Point is referenced both using the class name as a qualifier, in Point.origin, and using variables of the class type in field access expressions (§15.11), as in p.origin and q.origin. These two ways of accessing the origin class variable access the same object, evidenced by the fact that the value of the reference equality expression (§15.21.3):

-

q.origin==Point.origin
-
-is true. Further evidence is that the incrementation:

-

p.origin.useCount++;
-
-causes the value of q.origin.useCount to be 1; this is so because p.origin and q.origin refer to the same variable.

- -

8.3.1.2 final Fields

- -A field can be declared final (§4.5.4). Both class and instance variables (static and non-static fields) may be declared final.

- -It is a compile-time error if a blank final (§4.5.4) class variable is not definitely assigned (§16.7) by a static initializer (§8.7) of the class in which it is declared.

- -A blank final instance variable must be definitely assigned (§16.8) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.

- -

8.3.1.3 transient Fields

- -Variables may be marked transient to indicate that they are not part of the persistent state of an object.

- -If an instance of the class Point: -

class Point {
-	int x, y;
-	transient float rho, theta;
-}
-
-were saved to persistent storage by a system service, then only the fields x and y would be saved. This specification does not specify details of such services; see the specification of java.io.Serializable for an example of such a service.

- -

8.3.1.4 volatile Fields

- -As described in §17, the Java programming language allows threads that access shared variables to keep private working copies of the variables; this allows a more efficient implementation of multiple threads. These working copies need be reconciled with the master copies in the shared main memory only at prescribed synchronization points, namely when objects are locked or unlocked. As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

- -The Java programming language provides a second mechanism, volatile fields, that is more convenient for some purposes. - -

-A field may be declared volatile, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.

- -If, in the following example, one thread repeatedly calls the method one (but no more than Integer.MAX_VALUE times in all), and another thread repeatedly calls the method two: -

class Test {
-	static int i = 0, j = 0;
-	static void one() { i++; j++; }
-	static void two() {
-		System.out.println("i=" + i + " j=" + j);
-	}
-}
-
-then method two could occasionally print a value for j that is greater than the value of i, because the example includes no synchronization and, under the rules explained in §17, the shared values of i and j might be updated out of order.

- -One way to prevent this out-or-order behavior would be to declare methods one and two to be synchronized (§8.4.3.6): -

class Test {
-	static int i = 0, j = 0;
-	static synchronized void one() { i++; j++; }
-	static synchronized void two() {
-		System.out.println("i=" + i + " j=" + j);
-	}
-}
-
-This prevents method one and method two from being executed concurrently, and furthermore guarantees that the shared values of i and j are both updated before method one returns. Therefore method two never observes a value for j greater than that for i; indeed, it always observes the same value for i and j.

- -Another approach would be to declare i and j to be volatile: -

class Test {
-	static volatile int i = 0, j = 0;
-	static void one() { i++; j++; }
-	static void two() {
-		System.out.println("i=" + i + " j=" + j);
-	}
-}
-
- -This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, the shared value for j is never greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j. - -See §17 for more discussion and examples.

- -A compile-time error occurs if a final variable is also declared volatile.

- -

8.3.2 Initialization of Fields

- -If a field declarator contains a variable initializer, then it has the semantics of an assignment (§15.26) to the declared variable, and:

-

class Point {
-	int x = 1, y = 5;
-}
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		System.out.println(p.x + ", " + p.y);
-	}
-}
-
-produces the output:

-

1, 5
-
-because the assignments to x and y occur whenever a new Point is created.

- -Variable initializers are also used in local variable declaration statements (§14.4), where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.

- -It is a compile-time error if the evaluation of a variable initializer for a static field or for an instance variable of a named class (or of an interface) can complete abruptly with a checked exception (§11.2).

- -

8.3.2.1 Initializers for Class Variables

- -If a reference by simple name to any instance variable occurs in an initialization expression for a class variable, then a compile-time error occurs.

- -If the keyword this (§15.8.3) or the keyword super (§15.11.2, §15.12) occurs in an initialization expression for a class variable, then a compile-time error occurs.

- -One subtlety here is that, at run time, static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (§9.3.1). These variables are "constants" that will never be observed to have their default initial values (§4.5.5), even by devious programs. See §12.4.2 and §13.4.8 for more discussion. - -Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to class variables.

- -

8.3.2.2 Initializers for Instance Variables

- -Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later.

- -Thus the example: -

class Test {
-	float f = j;
-	static int j = 1;
-}
-
-compiles without error; it initializes j to 1 when class Test is initialized, and initializes f to the current value of j every time an instance of class Test is created.

- -Initialization expressions for instance variables are permitted to refer to the current object this (§15.8.3) and to use the keyword super (§15.11.2, §15.12).

- -Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to instance variables.

- -

8.3.2.3 Restrictions on the use of Fields during Initialization

- -The declaration of a member needs to appear before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

-

-A compile-time error occurs if any of the three requirements above are not met.

- -This means that a compile-time error results from the test program: -

	class Test {
-		int i = j;	// compile-time error: incorrect forward reference
-		int j = 1;
-	}
-
-whereas the following example compiles without error:

-

	class Test {
-		Test() { k = 2; }
-		int j = 1;
-		int i = j;
-		int k;
-	}
-
-even though the constructor (§8.8) for Test refers to the field k that is declared three lines later.

- -These restrictions are designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both: -

class Z {
-	static int i = j + 2; 
-	static int j = 4;
-}
-
-and:

-

class Z {
-	static { i = j + 2; }
-	static int i, j;
-	static { j = 4; }
-}
-
-result in compile-time errors. Accesses by methods are not checked in this way, so:

-

class Z {
-	static int peek() { return j; }
-	static int i = peek();
-	static int j = 1;
-}
-class Test {
-	public static void main(String[] args) {
-		System.out.println(Z.i);
-	}
-}
-
-produces the output:

-

0
-
-because the variable initializer for i uses the class method peek to access the value of the variable j before j has been initialized by its variable initializer, at which point it still has its default value (§4.5.5).

- -A more elaborate example is: -

class UseBeforeDeclaration {
-	static {
-		x = 100; // ok - assignment
-		int y = x + 1; // error - read before declaration
-		int v = x = 3; // ok - x at left hand side of assignment
-		int z = UseBeforeDeclaration.x * 2;
-	// ok - not accessed via simple name
-		Object o = new Object(){ 
-			void foo(){x++;} // ok - occurs in a different class
-			{x++;} // ok - occurs in a different class
-    		};
-  }
-	{
-		j = 200; // ok - assignment
-		j = j + 1; // error - right hand side reads before declaration
-		int k = j = j + 1; 
-		int n = j = 300; // ok - j at left hand side of assignment
-		int h = j++; // error - read before declaration
-		int l = this.j * 3; // ok - not accessed via simple name
-		Object o = new Object(){ 
-			void foo(){j++;} // ok - occurs in a different class
-			{ j = j + 1;} // ok - occurs in a different class
-		};
-	}
-	int w = x= 3; // ok - x at left hand side of assignment
-	int p = x; // ok - instance initializers may access static fields
-	static int u = (new Object(){int bar(){return x;}}).bar();
-	// ok - occurs in a different class
-	static int x;
-	int m = j = 4; // ok - j at left hand side of assignment
-	int o = (new Object(){int bar(){return j;}}).bar(); 
-	// ok - occurs in a different class
-	int j;
-}
-
-

8.3.3 Examples of Field Declarations

- -The following examples illustrate some (possibly subtle) points about field declarations.

- -

8.3.3.1 Example: Hiding of Class Variables

- -The example:

-

class Point {
-	static int x = 2;
-}
-class Test extends Point {
-	static double x = 4.7;
-	public static void main(String[] args) {
-		new Test().printX();
-	}
-	void printX() {
-		System.out.println(x + " " + super.x);
-	}
-}
-
-produces the output:

-

4.7 2
-
-because the declaration of x in class Test hides the definition of x in class Point, so class Test does not inherit the field x from its superclass Point. Within the declaration of class Test, the simple name x refers to the field declared within class Test. Code in class Test may refer to the field x of class Point as super.x (or, because x is static, as Point.x). If the declaration of Test.x is deleted:

-

class Point {
-	static int x = 2;
-}
-class Test extends Point {
-	public static void main(String[] args) {
-		new Test().printX();
-	}
-	void printX() {
-		System.out.println(x + " " + super.x);
-	}
-}
-
-then the field x of class Point is no longer hidden within class Test; instead, the simple name x now refers to the field Point.x. Code in class Test may still refer to that same field as super.x. Therefore, the output from this variant program is:

-

2 2
-
-

8.3.3.2 Example: Hiding of Instance Variables

- -This example is similar to that in the previous section, but uses instance variables rather than static variables. The code:

-

class Point {
-	int x = 2;
-}
-class Test extends Point {
-	double x = 4.7;
-	void printBoth() {
-		System.out.println(x + " " + super.x);
-	}
-	public static void main(String[] args) {
-		Test sample = new Test();
-		sample.printBoth();
-		System.out.println(sample.x + " " + 
-								((Point)sample).x);
-	}
-}
-
-produces the output:

-

4.7 2
-4.7 2
-
-because the declaration of x in class Test hides the definition of x in class Point, so class Test does not inherit the field x from its superclass Point. It must be noted, however, that while the field x of class Point is not inherited by class Test, it is nevertheless implemented by instances of class Test. In other words, every instance of class Test contains two fields, one of type int and one of type float. Both fields bear the name x, but within the declaration of class Test, the simple name x always refers to the field declared within class Test. Code in instance methods of class Test may refer to the instance variable x of class Point as super.x.

- -Code that uses a field access expression to access field x will access the field named x in the class indicated by the type of reference expression. Thus, the expression sample.x accesses a float value, the instance variable declared in class Test, because the type of the variable sample is Test, but the expression ((Point)sample).x accesses an int value, the instance variable declared in class Point, because of the cast to type Point. - -

If the declaration of x is deleted from class Test, as in the program: -

class Point {
-	static int x = 2;
-}
-class Test extends Point {
-	void printBoth() {
-		System.out.println(x + " " + super.x);
-	}
-	public static void main(String[] args) {
-		Test sample = new Test();
-		sample.printBoth();
-		System.out.println(sample.x + " " +
-												((Point)sample).x);
-	}
-}
-
-then the field x of class Point is no longer hidden within class Test. Within instance methods in the declaration of class Test, the simple name x now refers to the field declared within class Point. Code in class Test may still refer to that same field as super.x. The expression sample.x still refers to the field x within type Test, but that field is now an inherited field, and so refers to the field x declared in class Point. The output from this variant program is:

-

2 2
-2 2
-
-

8.3.3.3 Example: Multiply Inherited Fields

- -A class may inherit two or more fields with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited field by its simple name. A qualified name or a field access expression that contains the keyword super (§15.11.2) may be used to access such fields unambiguously. In the example:

-

interface Frob { float v = 2.0f; }
-class SuperTest { int v = 3; }
-class Test extends SuperTest implements Frob {
-	public static void main(String[] args) {
-		new Test().printV();
-	}
-	void printV() { System.out.println(v); }
-}
-
-the class Test inherits two fields named v, one from its superclass SuperTest and one from its superinterface Frob. This in itself is permitted, but a compile-time error occurs because of the use of the simple name v in method printV: it cannot be determined which v is intended.

- -The following variation uses the field access expression super.v to refer to the field named v declared in class SuperTest and uses the qualified name Frob.v to refer to the field named v declared in interface Frob: -

interface Frob { float v = 2.0f; }
-class SuperTest { int v = 3; }
-class Test extends SuperTest implements Frob {
-	public static void main(String[] args) {
-		new Test().printV();
-	}
-	void printV() {
-		System.out.println((super.v + Frob.v)/2);
-	}
-}
-
-It compiles and prints:

-

2.5
-
- -Even if two distinct inherited fields have the same type, the same value, and are both final, any reference to either field by simple name is considered ambiguous and results in a compile-time error. In the example: -
-interface Color { int RED=0, GREEN=1, BLUE=2; }
-interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; }
-class Test implements Color, TrafficLight {
-	public static void main(String[] args) {
-		System.out.println(GREEN);			// compile-time error
-		System.out.println(RED);		// compile-time error
-	}
-}
-
-it is not astonishing that the reference to GREEN should be considered ambiguous, because class Test inherits two different declarations for GREEN with different values. The point of this example is that the reference to RED is also considered ambiguous, because two distinct declarations are inherited. The fact that the two fields named RED happen to have the same type and the same unchanging value does not affect this judgment.

- -

8.3.3.4 Example: Re-inheritance of Fields

- -If the same field declaration is inherited from an interface by multiple paths, the field is considered to be inherited only once. It may be referred to by its simple name without ambiguity. For example, in the code:

-

public interface Colorable {
-	int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff;
-}
-public interface Paintable extends Colorable {
-	int MATTE = 0, GLOSSY = 1;
-}
-class Point { int x, y; }
-class ColoredPoint extends Point implements Colorable {
-	. . .
-}
-class PaintedPoint extends ColoredPoint implements Paintable 
-{
-	. . .       RED       . . .
-}
-
-the fields RED, GREEN, and BLUE are inherited by the class PaintedPoint both through its direct superclass ColoredPoint and through its direct superinterface Paintable. The simple names RED, GREEN, and BLUE may nevertheless be used without ambiguity within the class PaintedPoint to refer to the fields declared in interface Colorable.

- -

8.4 Method Declarations

- -A method declares executable code that can be invoked, passing a fixed number of values as arguments.

-

-The MethodModifiers are described in §8.4.3, the Throws clause in §8.4.4, and the MethodBody in §8.4.5. A method declaration either specifies the type of value that the method returns or uses the keyword void to indicate that the method does not return a value.

- -The Identifier in a MethodDeclarator may be used in a name to refer to the method. A class can declare a method with the same name as the class or a field, member class or member interface of the class.

- -For compatibility with older versions of the Java platform, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. This is supported by the obsolescent production:

-

-but should not be used in new code.

- -It is a compile-time error for the body of a class to have as members two methods with the same signature (§8.4.2) (name, number of parameters, and types of any parameters). Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (§6.5).

- -

8.4.1 Formal Parameters

- -The formal parameters of a method or constructor, if any, are specified by a list of comma-separated parameter specifiers. Each parameter specifier consists of a type (optionally preceded by the final modifier) and an identifier (optionally followed by brackets) that specifies the name of the parameter:

-

-The following is repeated from §8.3 to make the presentation here clearer:

-

-If a method or constructor has no parameters, only an empty pair of parentheses appears in the declaration of the method or constructor.

- -If two formal parameters of the same method or constructor are declared to have the same name (that is, their declarations mention the same Identifier), then a compile-time error occurs.

- -It is a compile-time error if a method or constructor parameter that is declared final is assigned to within the body of the method or constructor.

- -When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.

- -The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.

- -These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor. However, a parameter of a method or constructor may be shadowed anywhere inside a class declaration nested within that method or constructor. Such a nested class declaration could declare either a local class (§14.3) or an anonymous class (§15.9).

- -Formal parameters are referred to only using simple names, never by using qualified names (§6.6).

- -A method or constructor parameter of type float always contains an element of the float value set (§4.2.3); similarly, a method or constructor parameter of type double always contains an element of the double value set. It is not permitted for a method or constructor parameter of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a method parameter of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.

- -Where an actual argument expression corresponding to a parameter variable is not FP-strict (§15.4), evaluation of that actual argument expression is permitted to use intermediate values drawn from the appropriate extended-exponent value sets. Prior to being stored in the parameter variable the result of such an expression is mapped to the nearest value in the corresponding standard value set by method invocation conversion (§5.3).

- -

8.4.2 Method Signature

- -The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile-time error occurs.

- -The example: -

class Point implements Move {
-	int x, y;
-	abstract void move(int dx, int dy);
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-causes a compile-time error because it declares two move methods with the same signature. This is an error even though one of the declarations is abstract.

- -

8.4.3 Method Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a method declaration, or if a method declaration has more than one of the access modifiers public, protected, and private. A compile-time error occurs if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, strictfp, or synchronized. A compile-time error occurs if a method declaration that contains the keyword native also contains strictfp.

- -If two or more method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier. - -

8.4.3.1 abstract Methods

- -An abstract method declaration introduces the method as a member, providing its signature (name and number and type of parameters), return type, and throws clause (if any), but does not provide an implementation. The declaration of an abstract method m must appear directly within an abstract class (call it A); otherwise a compile-time error results. Every subclass of A that is not abstract must provide an implementation for m, or a compile-time error occurs as specified in §8.1.1.1.

- -It is a compile-time error for a private method to be declared abstract.

- -It would be impossible for a subclass to implement a private abstract method, because private methods are not inherited by subclasses; therefore such a method could never be used. - -

-It is a compile-time error for a static method to be declared abstract.

- -It is a compile-time error for a final method to be declared abstract.

- -An abstract class can override an abstract method by providing another abstract method declaration.

- -This can provide a place to put a documentation comment, or to declare that the set of checked exceptions (§11.2) that can be thrown by that method, when it is implemented by its subclasses, is to be more limited. For example, consider this code: -

class BufferEmpty extends Exception {
-	BufferEmpty() { super(); }
-	BufferEmpty(String s) { super(s); }
-}
-class BufferError extends Exception {
-	BufferError() { super(); }
-	BufferError(String s) { super(s); }
-}
-public interface Buffer {
-	char get() throws BufferEmpty, BufferError;
-}
-public abstract class InfiniteBuffer implements Buffer {
-	abstract char get() throws BufferError;
-}
-
- -The overriding declaration of method get in class InfiniteBuffer states that method get in any subclass of InfiniteBuffer never throws a BufferEmpty exception, putatively because it generates the data in the buffer, and thus can never run out of data. - -An instance method that is not abstract can be overridden by an abstract method.

- -For example, we can declare an abstract class Point that requires its subclasses to implement toString if they are to be complete, instantiable classes: -

abstract class Point {
-	int x, y;
-	public abstract String toString();
-}
-
-This abstract declaration of toString overrides the non-abstract toString method of class Object. (Class Object is the implicit direct superclass of class Point.) Adding the code:

-

class ColoredPoint extends Point {
-	int color;
-	public String toString() {
-		return super.toString() + ": color " + color; // error
-	}
-}
-
-results in a compile-time error because the invocation super.toString() refers to method toString in class Point, which is abstract and therefore cannot be invoked. Method toString of class Object can be made available to class ColoredPoint only if class Point explicitly makes it available through some other method, as in:

-

abstract class Point {
-	int x, y;
-	public abstract String toString();
-	protected String objString() { return super.toString(); }
-}
-class ColoredPoint extends Point {
-	int color;
-	public String toString() {
-		return objString() + ": color " + color;	// correct
-	}
-}
-
-

8.4.3.2 static Methods

- -A method that is declared static is called a class method. A class method is always invoked without reference to a particular object. An attempt to reference the current object using the keyword this or the keyword super in the body of a class method results in a compile-time error. It is a compile-time error for a static method to be declared abstract.

- -A method that is not declared static is called an instance method, and sometimes called a non-static method. An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

- -

8.4.3.3 final Methods

- -A method can be declared final to prevent subclasses from overriding or hiding it. It is a compile-time error to attempt to override or hide a final method.

- -A private method and all methods declared in a final class (§8.1.1.2) are implicitly final, because it is impossible to override them. It is permitted but not required for the declarations of such methods to redundantly include the final keyword.

- -It is a compile-time error for a final method to be declared abstract.

- -At run time, a machine-code generator or optimizer can "inline" the body of a final method, replacing an invocation of the method with the code in its body. The inlining process must preserve the semantics of the method invocation. In particular, if the target of an instance method invocation is null, then a NullPointerException must be thrown even if the method is inlined. The compiler must ensure that the exception will be thrown at the correct point, so that the actual arguments to the method will be seen to have been evaluated in the correct order prior to the method invocation.

- -Consider the example: -

final class Point {
-	int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-class Test {
-	public static void main(String[] args) {
-		Point[] p = new Point[100];
-		for (int i = 0; i < p.length; i++) {
-			p[i] = new Point();
-			p[i].move(i, p.length-1-i);
-		}
-	}
-}
-
-Here, inlining the method move of class Point in method main would transform the for loop to the form:

-

		for (int i = 0; i < p.length; i++) {
-			p[i] = new Point();
-			Point pi = p[i];
-			int j = p.length-1-i;
-			pi.x += i;
-			pi.y += j;
-		}
-
-The loop might then be subject to further optimizations.

- -Such inlining cannot be done at compile time unless it can be guaranteed that Test and Point will always be recompiled together, so that whenever Point-and specifically its move method-changes, the code for Test.main will also be updated. - -

8.4.3.4 native Methods

- -A method that is native is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN, or assembly language. The body of a native method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.

- -A compile-time error occurs if a native method is declared abstract.

- -For example, the class RandomAccessFile of the package java.io might declare the following native methods: -

package java.io;
-public class RandomAccessFile
-	implements DataOutput, DataInput
-{	. . .
-	public native void open(String name, boolean writeable)
-		throws IOException;
-	public native int readBytes(byte[] b, int off, int len)
-		throws IOException;
-	public native void writeBytes(byte[] b, int off, int len)
-		throws IOException;
-	public native long getFilePointer() throws IOException;
-	public native void seek(long pos) throws IOException;
-	public native long length() throws IOException;
-	public native void close() throws IOException;
-}
-
-

8.4.3.5 strictfp Methods

- -The effect of the strictfp modifier is to make all float or double expressions within the method body be explicitly FP-strict (§15.4).

- -

8.4.3.6 synchronized Methods

- -A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method, the lock associated with the Class object for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.

- -These are the same locks that can be used by the synchronized statement (§14.18); thus, the code: -

class Test {
-	int count;
-	synchronized void bump() { count++; }
-	static int classCount;
-	static synchronized void classBump() {
-		classCount++;
-	}
-}
-
-has exactly the same effect as:

-

class BumpTest {
-	int count;
-	void bump() {
-		synchronized (this) {
-			count++;
-		}
-	}
-	static int classCount;
-	static void classBump() {
-		try {
-			synchronized (Class.forName("BumpTest")) {
-				classCount++;
-			}
-		} catch (ClassNotFoundException e) {
-				...
-		}
-	}
-}
-
-The more elaborate example:

-

public class Box {
-	private Object boxContents;
-	public synchronized Object get() {
-		Object contents = boxContents;
-		boxContents = null;
-		return contents;
-	}
-	public synchronized boolean put(Object contents) {
-		if (boxContents != null)
-			return false;
-		boxContents = contents;
-		return true;
-	}
-}
-
-defines a class which is designed for concurrent use. Each instance of the class Box has an instance variable contents that can hold a reference to any object. You can put an object in a Box by invoking put, which returns false if the box is already full. You can get something out of a Box by invoking get, which returns a null reference if the box is empty.

- -If put and get were not synchronized, and two threads were executing methods for the same instance of Box at the same time, then the code could misbehave. It might, for example, lose track of an object because two invocations to put occurred at the same time. -

- -See §17 for more discussion of threads and locks. - -

8.4.4 Method Throws

- -A throws clause is used to declare any checked exceptions (§11.2) that can result from the execution of a method or constructor:

-

-A compile-time error occurs if any ClassType mentioned in a throws clause is not the class Throwable or a subclass of Throwable. It is permitted but not required to mention other (unchecked) exceptions in a throws clause.

- -For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a throws clause in the declaration of the method or constructor.

- -The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a throws clause. The Java programming language thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way. - -

-The predefined exceptions that are not checked in this way are those for which declaring every possible occurrence would be unimaginably inconvenient:

-

-A method that overrides or hides another method (§8.4.6), including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.

- -More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. If n has a throws clause that mentions any checked exception types, then m must have a throws clause, and for every checked exception type listed in the throws clause of n, that same exception class or one of its superclasses must occur in the throws clause of m; otherwise, a compile-time error occurs.

- -See §11 for more information about exceptions and a large example.

- -

8.4.5 Method Body

- -A method body is either a block of code that implements the method or simply a semicolon, indicating the lack of an implementation. The body of a method must be a semicolon if and only if the method is either abstract (§8.4.3.1) or native (§8.4.3.4).

-

-A compile-time error occurs if a method declaration is either abstract or native and has a block for its body. A compile-time error occurs if a method declaration is neither abstract nor native and has a semicolon for its body.

- -If an implementation is to be provided for a method but the implementation requires no executable code, the method body should be written as a block that contains no statements: "{ }". - -

-If a method is declared void, then its body must not contain any return statement (§14.16) that has an Expression.

- -If a method is declared to have a return type, then every return statement (§14.16) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.1).

- -In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body." -

- -Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example: -

class DizzyDean {
-	int pitch() { throw new RuntimeException("90 mph?!"); }
-}
-
-

8.4.6 Inheritance, Overriding, and Hiding

- -A class inherits from its direct superclass and direct superinterfaces all the non-private methods (whether abstract or not) of the superclass and superinterfaces that are accessible to code in the class and are neither overridden (§8.4.6.1) nor hidden (§8.4.6.2) by a declaration in the class.

- -

8.4.6.1 Overriding (by Instance Methods)

- -An instance method m1 declared in a class C overrides another method with the same signature, m2, declared in class A if both -
    - -
  1. C is a subclass of A. - -
  2. Either -
      - -
    • m2 is non-private and accessible from C, or - -
    • m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2. -
    -
- -Moreover, if m1 is not abstract, then m1 is said to implement any and all declarations of abstract methods that it overrides.

- -A compile-time error occurs if an instance method overrides a static method.

- -In this respect, overriding of methods differs from hiding of fields (§8.3), for it is permissible for an instance variable to hide a static variable. - -

-An overridden method can be accessed by using a method invocation expression (§15.12) that contains the keyword super. Note that a qualified name or a cast to a superclass type is not effective in attempting to access an overridden method; in this respect, overriding of methods differs from hiding of fields. See §15.12.4.9 for discussion and examples of this point. - -

-The presence or absence of the strictfp modifier has absolutely no effect on the rules for overriding methods and implementing abstract methods. For example, it is permitted for a method that is not FP-strict to override an FP-strict method and it is permitted for an FP-strict method to override a method that is not FP-strict.

- -

8.4.6.2 Hiding (by Class Methods)

- -If a class declares a static method, then the declaration of that method is said to hide any and all methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. A compile-time error occurs if a static method hides an instance method.

- -In this respect, hiding of methods differs from hiding of fields (§8.3), for it is permissible for a static variable to hide an instance variable. Hiding is also distinct from shadowing (§6.3.1) and obscuring (§6.3.2). - -

-A hidden method can be accessed by using a qualified name or by using a method invocation expression (§15.12) that contains the keyword super or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields. - -

8.4.6.3 Requirements in Overriding and Hiding

- -If a method declaration overrides or hides the declaration of another method, then a compile-time error occurs if they have different return types or if one has a return type and the other is void. Moreover, a method declaration must not have a throws clause that conflicts (§8.4.4) with that of any method that it overrides or hides; otherwise, a compile-time error occurs.

- -In these respects, overriding of methods differs from hiding of fields (§8.3), for it is permissible for a field to hide a field of another type. - -

-The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:

-

-Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass. - -

8.4.6.4 Inheriting Methods with the Same Signature

- -It is possible for a class to inherit more than one method with the same signature. Such a situation does not in itself cause a compile-time error. There are then two possible cases:

-

-It is not possible for two or more inherited methods with the same signature not to be abstract, because methods that are not abstract are inherited only from the direct superclass, not from superinterfaces.

- -There might be several paths by which the same method declaration might be inherited from an interface. This fact causes no difficulty and never, of itself, results in a compile-time error.

- -

8.4.7 Overloading

- -If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.

- -Methods are overridden on a signature-by-signature basis.

- -If, for example, a class declares two public methods with the same name, and a subclass overrides one of them, the subclass still inherits the other method. In this respect, the Java programming language differs from C++. - -

-When a method is invoked (§15.12), the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4). - -

8.4.8 Examples of Method Declarations

- -The following examples illustrate some (possibly subtle) points about method declarations.

- -

8.4.8.1 Example: Overriding

- -In the example:

-

class Point {
-	int x = 0, y = 0;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-class SlowPoint extends Point {
-	int xLimit, yLimit;
-	void move(int dx, int dy) {
-		super.move(limit(dx, xLimit), limit(dy, yLimit));
-	}
-	static int limit(int d, int limit) {
-		return d > limit ? limit : d < -limit ? -limit : d;
-	}
-}
-
-the class SlowPoint overrides the declarations of method move of class Point with its own move method, which limits the distance that the point can move on each invocation of the method. When the move method is invoked for an instance of class SlowPoint, the overriding definition in class SlowPoint will always be called, even if the reference to the SlowPoint object is taken from a variable whose type is Point.

- -

8.4.8.2 Example: Overloading, Overriding, and Hiding

- -In the example:

-

class Point {
-	int x = 0, y = 0;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	int color;
-}
-class RealPoint extends Point {
-	float x = 0.0f, y = 0.0f;
-	void move(int dx, int dy) { move((float)dx, (float)dy); }
-	void move(float dx, float dy) { x += dx; y += dy; }
-}
-
-the class RealPoint hides the declarations of the int instance variables x and y of class Point with its own float instance variables x and y, and overrides the method move of class Point with its own move method. It also overloads the name move with another method with a different signature (§8.4.2).

- -In this example, the members of the class RealPoint include the instance variable color inherited from the class Point, the float instance variables x and y declared in RealPoint, and the two move methods declared in RealPoint. - -

-Which of these overloaded move methods of class RealPoint will be chosen for any particular method invocation will be determined at compile time by the overloading resolution procedure described in §15.12. - -

8.4.8.3 Example: Incorrect Overriding

- -This example is an extended variation of that in the preceding section:

-

class Point {
-	int x = 0, y = 0, color;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	int getX() { return x; }
-	int getY() { return y; }
-}
-class RealPoint extends Point {
-	float x = 0.0f, y = 0.0f;
-	void move(int dx, int dy) { move((float)dx, (float)dy); }
-	void move(float dx, float dy) { x += dx; y += dy; }
-	float getX() { return x; }
-	float getY() { return y; }
-}
-
-Here the class Point provides methods getX and getY that return the values of its fields x and y; the class RealPoint then overrides these methods by declaring methods with the same signature. The result is two errors at compile time, one for each method, because the return types do not match; the methods in class Point return values of type int, but the wanna-be overriding methods in class RealPoint return values of type float.

- -

8.4.8.4 Example: Overriding versus Hiding

- -This example corrects the errors of the example in the preceding section:

-

class Point {
-	int x = 0, y = 0;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	int getX() { return x; }
-	int getY() { return y; }
-	int color;
-}
-class RealPoint extends Point {
-	float x = 0.0f, y = 0.0f;
-	void move(int dx, int dy) { move((float)dx, (float)dy); }
-	void move(float dx, float dy) { x += dx; y += dy; }
-	int getX() { return (int)Math.floor(x); }
-	int getY() { return (int)Math.floor(y); }
-}
-
-Here the overriding methods getX and getY in class RealPoint have the same return types as the methods of class Point that they override, so this code can be successfully compiled.

- -Consider, then, this test program: -

class Test {
-	public static void main(String[] args) {
-		RealPoint rp = new RealPoint();
-		Point p = rp;
-		rp.move(1.71828f, 4.14159f);
-		p.move(1, -1);
-		show(p.x, p.y);
-		show(rp.x, rp.y);
-		show(p.getX(), p.getY());
-		show(rp.getX(), rp.getY());
-	}
-	static void show(int x, int y) {
-		System.out.println("(" + x + ", " + y + ")");
-	}
-	static void show(float x, float y) {
-		System.out.println("(" + x + ", " + y + ")");
-	}
-}
-
-The output from this program is:

-

(0, 0)
-(2.7182798, 3.14159)
-(2, 3)
-(2, 3)
-
- -The first line of output illustrates the fact that an instance of RealPoint actually contains the two integer fields declared in class Point; it is just that their names are hidden from code that occurs within the declaration of class RealPoint (and those of any subclasses it might have). When a reference to an instance of class RealPoint in a variable of type Point is used to access the field x, the integer field x declared in class Point is accessed. The fact that its value is zero indicates that the method invocation p.move(1, -1) did not invoke the method move of class Point; instead, it invoked the overriding method move of class RealPoint. - -

The second line of output shows that the field access rp.x refers to the field x declared in class RealPoint. This field is of type float, and this second line of output accordingly displays floating-point values. Incidentally, this also illustrates the fact that the method name show is overloaded; the types of the arguments in the method invocation dictate which of the two definitions will be invoked. - -

The last two lines of output show that the method invocations p.getX() and rp.getX() each invoke the getX method declared in class RealPoint. Indeed, there is no way to invoke the getX method of class Point for an instance of class RealPoint from outside the body of RealPoint, no matter what the type of the variable we may use to hold the reference to the object. Thus, we see that fields and methods behave differently: hiding is different from overriding. - -

8.4.8.5 Example: Invocation of Hidden Class Methods

- -A hidden class (static) method can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods. The example:

-

class Super {
-	static String greeting() { return "Goodnight"; }
-	String name() { return "Richard"; }
-}
-class Sub extends Super {
-	static String greeting() { return "Hello"; }
-	String name() { return "Dick"; }
-}
-class Test {
-	public static void main(String[] args) {
-		Super s = new Sub();
-		System.out.println(s.greeting() + ", " + s.name());
-	}
-}
-
-produces the output:

-

Goodnight, Dick
-
-because the invocation of greeting uses the type of s, namely Super, to figure out, at compile time, which class method to invoke, whereas the invocation of name uses the class of s, namely Sub, to figure out, at run time, which instance method to invoke.

- -

8.4.8.6 Large Example of Overriding

- -Overriding makes it easy for subclasses to extend the behavior of an existing class, as shown in this example:

-

import java.io.OutputStream;
-import java.io.IOException;
-class BufferOutput {
-	private OutputStream o;
-	BufferOutput(OutputStream o) { this.o = o; }
-	protected byte[] buf = new byte[512];
-	protected int pos = 0;
-	public void putchar(char c) throws IOException {
-		if (pos == buf.length)
-			flush();
-		buf[pos++] = (byte)c;
-	}
-	public void putstr(String s) throws IOException {
-		for (int i = 0; i < s.length(); i++)
-			putchar(s.charAt(i));
-	}
-	public void flush() throws IOException {
-		o.write(buf, 0, pos);
-		pos = 0;
-	}
-}
-class LineBufferOutput extends BufferOutput {
-	LineBufferOutput(OutputStream o) { super(o); }
-	public void putchar(char c) throws IOException {
-		super.putchar(c);
-		if (c == '\n')
-			flush();
-	}
-}
-class Test {
-	public static void main(String[] args)
-		throws IOException
-	{
-		LineBufferOutput lbo =
-			new LineBufferOutput(System.out);
-		lbo.putstr("lbo\nlbo");
-		System.out.print("print\n");
-		lbo.putstr("\n");
-	}
-}
-
-This example produces the output:

-

lbo
-print
-lbo
-
- -The class BufferOutput implements a very simple buffered version of an OutputStream, flushing the output when the buffer is full or flush is invoked. The subclass LineBufferOutput declares only a constructor and a single method putchar, which overrides the method putchar of BufferOutput. It inherits the methods putstr and flush from class BufferOutput. -

- -In the putchar method of a LineBufferOutput object, if the character argument is a newline, then it invokes the flush method. The critical point about overriding in this example is that the method putstr, which is declared in class BufferOutput, invokes the putchar method defined by the current object this, which is not necessarily the putchar method declared in class BufferOutput. - -

-Thus, when putstr is invoked in main using the LineBufferOutput object lbo, the invocation of putchar in the body of the putstr method is an invocation of the putchar of the object lbo, the overriding declaration of putchar that checks for a newline. This allows a subclass of BufferOutput to change the behavior of the putstr method without redefining it. - -

-Documentation for a class such as BufferOutput, which is designed to be extended, should clearly indicate what is the contract between the class and its subclasses, and should clearly indicate that subclasses may override the putchar method in this way. The implementor of the BufferOutput class would not, therefore, want to change the implementation of putstr in a future implementation of BufferOutput not to use the method putchar, because this would break the preexisting contract with subclasses. See the further discussion of binary compatibility in §13, especially §13.2. - -

8.4.8.7 Example: Incorrect Overriding because of Throws

- -This example uses the usual and conventional form for declaring a new exception type, in its declaration of the class BadPointException:

-

class BadPointException extends Exception {
-	BadPointException() { super(); }
-	BadPointException(String s) { super(s); }
-}
-class Point {
-	int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-class CheckedPoint extends Point {
-	void move(int dx, int dy) throws BadPointException {
-		if ((x + dx) < 0 || (y + dy) < 0)
-			throw new BadPointException();
-		x += dx; y += dy;
-	}
-}
-
-This example results in a compile-time error, because the override of method move in class CheckedPoint declares that it will throw a checked exception that the move in class Point has not declared. If this were not considered an error, an invoker of the method move on a reference of type Point could find the contract between it and Point broken if this exception were thrown.

- -Removing the throws clause does not help: -

class CheckedPoint extends Point {
-	void move(int dx, int dy) {
-		if ((x + dx) < 0 || (y + dy) < 0)
-			throw new BadPointException();
-		x += dx; y += dy;
-	}
-}
-
- -

-A different compile-time error now occurs, because the body of the method move cannot throw a checked exception, namely BadPointException, that does not appear in the throws clause for move. - -

8.5 Member Type Declarations

- -A member class is a class whose declaration is directly enclosed in another class or interface declaration. Similarly, a member interface is an interface whose declaration is directly enclosed in another class or interface declaration. The scope (§6.3) of a member class or interface is specified in §8.1.5.

- -If the class declares a member type with a certain name, then the declaration of that type is said to hide any and all accessible declarations of member types with the same name in superclasses and superinterfaces of the class.

- -Within a class C, a declaration d of a member type named n shadows the declarations of any other types named n that are in scope at the point where d occurs.

- -If a member class or interface declared with simple name C is directly enclosed within the declaration of a class with fully qualified name N, then the member class or interface has the fully qualified name N.C.

- -A class may inherit two or more type declarations with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited class or interface by its simple name.

- -If the same type declaration is inherited from an interface by multiple paths, the class or interface is considered to be inherited only once. It may be referred to by its simple name without ambiguity.

- -

8.5.1 Access Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if a member type declaration has more than one of the access modifiers public, protected, and private.

- -

8.5.2 Static Member Type Declarations

- -The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.

- -It is a compile-time error if a static class contains a usage of a non-static member of an enclosing class.

- -Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier.

- -

8.6 Instance Initializers

- -An instance initializer declared in a class is executed when an instance of the class is created (§15.9), as specified in §8.8.5.1.

-

-An instance initializer of a named class may not throw a checked exception unless that exception or one of its superclasses is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor. An instance initializer in an anonymous class (§15.9.5) can throw any exceptions.

- -The rules above distinguish between instance initializers in named and anonymous classes. This distinction is deliberate. A given anonymous class is only instantiated at a single point in a program. It is therefore possible to directly propagate information about what exceptions might be raised by an anonymous class' instance initializer to the surrounding expression. Named classes, on the other hand, can be instantiated in many places. Therefore the only way to propagate information about what exceptions might be raised by an instance initializer of a named class is through the throws clauses of its constructors. It follows that a more liberal rule can be used in the case of anonymous classes. Similar comments apply to instance variable initializers. - -

-It is a compile-time error if an instance initializer cannot complete normally (§14.20). If a return statement (§14.16) appears anywhere within an instance initializer, then a compile-time error occurs.

- -Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to instance variables.

- -Instance initializers are permitted to refer to the current object this (§15.8.3) and to use the keyword super (§15.11.2, §15.12).

- -

8.7 Static Initializers

- -Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).

-

-It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.6) with a checked exception (§11.2). It is a compile-time error if a static initializer cannot complete normally (§14.20).

- -The static initializers and class variable initializers are executed in textual order.

- -Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to class variables.

- -If a return statement (§14.16) appears anywhere within a static initializer, then a compile-time error occurs.

- -If the keyword this (§15.8.3) or the keyword super (§15.11, §15.12) appears anywhere within a static initializer, then a compile-time error occurs.

- -

8.8 Constructor Declarations

- -A constructor is used in the creation of an object that is an instance of a class:

-

-The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration; otherwise a compile-time error occurs. In all other respects, the constructor declaration looks just like a method declaration that has no result type.

- -

- -Here is a simple example: -

class Point {
-	int x, y;
-	Point(int x, int y) { this.x = x; this.y = y; }
-}
-
-Constructors are invoked by class instance creation expressions (§15.9), by the conversions and concatenations caused by the string concatenation operator + (§15.18.1), and by explicit constructor invocations from other constructors (§8.8.5). Constructors are never invoked by method invocation expressions (§15.12).

- -Access to constructors is governed by access modifiers (§6.6).

- -This is useful, for example, in preventing instantiation by declaring an inaccessible constructor (§8.8.8). - -Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

- -

8.8.1 Formal Parameters

- -The formal parameters of a constructor are identical in structure and behavior to the formal parameters of a method (§8.4.1).

- -

8.8.2 Constructor Signature

- -The signature of a constructor consists of the number and types of formal parameters to the constructor. A class may not declare two constructors with the same signature, or a compile-time error occurs.

- -

8.8.3 Constructor Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a constructor declaration, or if a constructor declaration has more than one of the access modifiers public, protected, and private.

- -Unlike methods, a constructor cannot be abstract, static, final, native, strictfp, or synchronized. A constructor is not inherited, so there is no need to declare it final and an abstract constructor could never be implemented. A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static. There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work. The lack of native constructors is an arbitrary language design choice that makes it easy for an implementation of the Java virtual machine to verify that superclass constructors are always properly invoked during object creation. - -

Note that a ConstructorModifier cannot be declared strictfp. This difference in the definitions for ConstructorModifier and MethodModifier (§8.4.3) is an intentional language design choice; it effectively ensures that a constructor is FP-strict (§15.4) if and only if its class is FP-strict. - - -

8.8.4 Constructor Throws

- -The throws clause for a constructor is identical in structure and behavior to the throws clause for a method (§8.4.4).

- -

8.8.5 Constructor Body

- -The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.5.1).

-

-It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.

- -If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

- -Except for the possibility of explicit constructor invocations, the body of a constructor is like the body of a method (§8.4.5). A return statement (§14.16) may be used in the body of a constructor if it does not include an expression.

- -In the example: -

class Point {
-	int x, y;
-	Point(int x, int y) { this.x = x; this.y = y; }
-}
-class ColoredPoint extends Point {
-	static final int WHITE = 0, BLACK = 1;
-	int color;
-	ColoredPoint(int x, int y) {
-		this(x, y, WHITE);
-	}
-	ColoredPoint(int x, int y, int color) {
-		super(x, y);
-		this.color = color;
-	}
-}
-
-the first constructor of ColoredPoint invokes the second, providing an additional argument; the second constructor of ColoredPoint invokes the constructor of its superclass Point, passing along the coordinates.

- -§12.5 and §15.9 describe the creation and initialization of new class instances.

- -

8.8.5.1 Explicit Constructor Invocations

- -

- -Explicit constructor invocation statements can be divided into two kinds:

-

class Outer {
-	class Inner{}
-}
-class ChildOfInner extends Outer.Inner {
-	ChildOfInner(){(new Outer()).super();}
-}
-
- -An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

- -For example, if the first constructor of ColoredPoint in the example above were changed to: -

ColoredPoint(int x, int y) {
-	this(x, y, color);
-}
-
-then a compile-time error would occur, because an instance variable cannot be used within a superclass constructor invocation.

- -If an anonymous class instance creation expression appears within an explicit constructor invocation statement, then the anonymous class may not refer to any of the enclosing instances of the class whose constructor is being invoked.

- -For example: -

class Top {
-	int x;
-	class Dummy {
-		Dummy(Object o) {}
-	}
-	class Inside extends Dummy {
-		Inside() {
-			super(new Object() { int r = x; }); // error
-		}
-		Inside(final int y) {
-			super(new Object() { int r = y; }); // correct
-		}
-	}
-}
-
-Let C be the class being instantiated, let S be the direct superclass of C, and let i be the instance being created. The evaluation of an explicit constructor invocation proceeds as follows:

-

-

8.8.6 Constructor Overloading

- -Overloading of constructors is identical in behavior to overloading of methods. The overloading is resolved at compile time by each class instance creation expression (§15.9).

- -

8.8.7 Default Constructor

- -If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:

-

-A compile-time error occurs if a default constructor is provided by the compiler but the superclass does not have an accessible constructor that takes no arguments.

- -

A default constructor has no throws clause.

-It follows that is the nullary constructor of the superclass has a -throws clause, then a compile-time error will occur. -

- -If the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

- -Thus, the example: -

public class Point {
-	int x, y;
-}
-
-is equivalent to the declaration:

-

public class Point {
-	int x, y;
-	public Point() { super(); }
-}
-
-where the default constructor is public because the class Point is public.

- -The rule that the default constructor of a class has the same access modifier as the class itself is simple and intuitive. Note, however, that this does not imply that the constructor is accessible whenever the class is accessible. Consider -

package p1;
-public class Outer {
- 	protected class Inner{}
-}
-package p2;
-class SonOfOuter extends p1.Outer {
-	void foo() {
- 		new Inner(); // compile-time access error
-	}
-}
-
-
-The constructor for Inner is protected. However, the constructor is protected relative to Inner, while Inner is protected relative to Outer. So, Inner is accessible in SonOfOuter, since it is a subclass of Outer. Inner's constructor is not accessible in SonOfOuter, because the class SonOfOuter is not a subclass of Inner! Hence, even though Inner is accessible, its default constructor is not.

- -

8.8.8 Preventing Instantiation of a Class

- -A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, to prevent the creation of an implicit constructor, and declaring all constructors to be private. A public class can likewise prevent the creation of instances outside its package by declaring at least one constructor, to prevent creation of a default constructor with public access, and declaring no constructor that is public.

- -Thus, in the example: -

class ClassOnly {
-	private ClassOnly() { }
-	static String just = "only the lonely";
-}
-
-the class ClassOnly cannot be instantiated, while in the example:

-

package just;
-public class PackageOnly {
-	PackageOnly() { }
-	String[] justDesserts = { "cheesecake", "ice cream" };
-}
-
-the class PackageOnly can be instantiated only within the package just, in which it is declared. -

- - -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

-Java Language Specification (HTML generated by Suzette Pelouch on May 19, 2000)
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - Interfaces - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-



- - -

-CHAPTER - 9

- -

Interfaces

-

- -An interface declaration introduces a new reference type whose members are classes, interfaces, constants and abstract methods. This type has no implementation, but otherwise unrelated classes can implement it by providing implementations for its abstract methods.

- -A nested interface is any interface whose declaration occurs within the body of another class or interface. A top-level interface is an interface that is not a nested interface.

- -This chapter discusses the common semantics of all interfaces-top-level (§7.6) and nested (§8.5, §9.5). Details that are specific to particular kinds of interfaces are discussed in the sections dedicated to these constructs.

- -Programs can use interfaces to make it unnecessary for related classes to share a common abstract superclass or to add methods to Object. - -An interface may be declared to be a direct extension of one or more other interfaces, meaning that it implicitly specifies all the member types, abstract methods and constants of the interfaces it extends, except for any member types and constants that it may hide.

- -A class may be declared to directly implement one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do. This (multiple) interface inheritance allows objects to support (multiple) common behaviors without sharing any implementation.

- -A variable whose declared type is an interface type may have as its value a reference to any instance of a class which implements the specified interface. It is not sufficient that the class happen to implement all the abstract methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface.

- -

9.1 Interface Declarations

- -An interface declaration specifies a new named reference type:

-

-The Identifier in an interface declaration specifies the name of the interface. A compile-time error occurs if an interface has the same simple name as any of its enclosing classes or interfaces.

- -

9.1.1 Interface Modifiers

- -An interface declaration may include interface modifiers:

-

-The access modifier public is discussed in §6.6. Not all modifiers are applicable to all kinds of interface declarations. The access modifiers protected and private pertain only to member interfaces within a directly enclosing class declaration (§8.5) and are discussed in §8.5.1. The access modifier static pertains only to member interfaces (§8.5, §9.5). A compile-time error occurs if the same modifier appears more than once in an interface declaration.

- -

9.1.1.1 abstract Interfaces

- -Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.

- -

9.1.1.2 strictfp Interfaces

- -The effect of the strictfp modifier is to make all float or double expressions within the interface declaration be explicitly FP-strict (§15.4).

- -This implies that all nested types declared in the interface are implicitly strictfp.

- -

9.1.2 Superinterfaces and Subinterfaces

- -If an extends clause is provided, then the interface being declared extends each of the other named interfaces and therefore inherits the member types, methods, and constants of each of the other named interfaces. These other named interfaces are the direct superinterfaces of the interface being declared. Any class that implements the declared interface is also considered to implement all the interfaces that this interface extends.

-

-The following is repeated from §4.2 to make the presentation here clearer:

-

-Each InterfaceType in the extends clause of an interface declaration must name an accessible interface type; otherwise a compile-time error occurs.

- -An interface I directly depends on a type T if T is mentioned in the extends clause of I either as a superinterface or as a qualifier within a superinterface name. An interface I depends on a reference type T if any of the following conditions hold:

-

-A compile-time error occurs if an interface depends on itself.

- -While every class is an extension of class Object, there is no single interface of which all interfaces are extensions.

- -The superinterface relationship is the transitive closure of the direct superinterface relationship. An interface K is a superinterface of interface I if either of the following is true:

-

-Interface I is said to be a subinterface of interface K whenever K is a superinterface of I.

- -

9.1.3 Interface Body and Member Declarations

- -The body of an interface may declare members of the interface:

-

-The scope of the declaration of a member m declared in or inherited by an interface type I is the entire body of I, including any nested type declarations.

- -

9.1.4 Access to Interface Member Names

- -All interface members are implicitly public. They are accessible outside the package where the interface is declared if the interface is also declared public or protected, in accordance with the rules of §6.6.

- -

9.2 Interface Members

- -The members of an interface are:

-

-It follows that it is a compile-time error if the interface declares a method with the same signature and different return type or incompatible throws clause.

- -The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields, classes, and interfaces that it hides and methods that it overrides.

- -

9.3 Field (Constant) Declarations

- -Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

- -If the interface declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superinterfaces of the interface.

- -It is a compile-time error for the body of an interface declaration to declare two fields with the same name.

- -It is possible for an interface to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the interface to refer to either field by its simple name will result in a compile-time error, because such a reference is ambiguous.

- -There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.

- -

9.3.1 Initialization of Fields in Interfaces

- -Every field in the body of an interface must have an initialization expression, which need not be a constant expression. The variable initializer is evaluated and the assignment performed exactly once, when the interface is initialized (§12.4).

- -A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface.

- -Thus: -

interface Test {
-	float f = j;
-	int j = 1;
-	int k = k+1;
-}
-
-causes two compile-time errors, because j is referred to in the initialization of f before j is declared and because the initialization of k refers to k itself.

- -One subtlety here is that, at run time, fields that are initialized with compile-time constant values are initialized first. This applies also to static final fields in classes (§8.3.2.1). This means, in particular, that these fields will never be observed to have their default initial values (§4.5.5), even by devious programs. See §12.4.2 and §13.4.8 for more discussion. -

- -If the keyword this (§15.8.3) or the keyword super (15.11.2, 15.12) occurs in an initialization expression for a field of an interface, then unless the occurrence is within the body of an anonymous class (§15.9.5), a compile-time error occurs.

- -

9.3.2 Examples of Field Declarations

- -The following example illustrates some (possibly subtle) points about field declarations.

- -

9.3.2.1 Ambiguous Inherited Fields

- -If two fields with the same name are inherited by an interface because, for example, two of its direct superinterfaces declare fields with that name, then a single ambiguous member results. Any use of this ambiguous member will result in a compile-time error. Thus in the example:

-

interface BaseColors {
-	int RED = 1, GREEN = 2, BLUE = 4;
-}
-interface RainbowColors extends BaseColors {
-	int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7;
-}
-interface PrintColors extends BaseColors {
-	int YELLOW = 8, CYAN = 16, MAGENTA = 32;
-}
-interface LotsOfColors extends RainbowColors, PrintColors {
-	int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90;
-}
-
-the interface LotsOfColors inherits two fields named YELLOW. This is all right as long as the interface does not contain any reference by simple name to the field YELLOW. (Such a reference could occur within a variable initializer for a field.)

- -Even if interface PrintColors were to give the value 3 to YELLOW rather than the value 8, a reference to field YELLOW within interface LotsOfColors would still be considered ambiguous. -

- -

9.3.2.2 Multiply Inherited Fields

- -If a single field is inherited multiple times from the same interface because, for example, both this interface and one of this interface's direct superinterfaces extend the interface that declares the field, then only a single member results. This situation does not in itself cause a compile-time error.

- -In the example in the previous section, the fields RED, GREEN, and BLUE are inherited by interface LotsOfColors in more than one way, through interface RainbowColors and also through interface PrintColors, but the reference to field RED in interface LotsOfColors is not considered ambiguous because only one actual declaration of the field RED is involved. -

- -

9.4 Abstract Method Declarations

- -The access modifier public is discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in an abstract method declaration.

- -Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.

- -Every method declaration in the body of an interface is implicitly public.

- -For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces. - -

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

- -Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.

- -Note that a method declared in an interface must not be declared strictfp or native or synchronized, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties. However, a method declared in an interface may be implemented by a method that is declared strictfp or native or synchronized in a class that implements the interface.

- -It is a compile-time error for the body of an interface to declare, explicitly or implicitly, two methods with the same signature (name, number of parameters, and types of any parameters) (§8.4.2). However, an interface may inherit several methods with the same signature (§9.4.1).

- -Note that a method declared in an interface must not be declared final or a compile-time error occurs. However, a method declared in an interface may be implemented by a method that is declared final in a class that implements the interface.

- -

9.4.1 Inheritance and Overriding

- -If the interface declares a method, then the declaration of that method is said to override any and all methods with the same signature in the superinterfaces of the interface.

- -If a method declaration in an interface overrides the declaration of a method in another interface, a compile-time error occurs if the methods have different return types or if one has a return type and the other is void. Moreover, a method declaration must not have a throws clause that conflicts (§8.4.4) with that of any method that it overrides; otherwise, a compile-time error occurs.

- -Methods are overridden on a signature-by-signature basis. If, for example, an interface declares two public methods with the same name, and a subinterface overrides one of them, the subinterface still inherits the other method.

- -An interface inherits from its direct superinterfaces all methods of the superinterfaces that are not overridden by a declaration in the interface.

- -It is possible for an interface to inherit more than one method with the same signature (§8.4.2). Such a situation does not in itself cause a compile-time error. The interface is considered to inherit all the methods. However, a compile-time error occurs if, for any two such inherited methods, either they have different return types or one has a return type and the other is void. (The throws clauses do not cause errors in this case.) There might be several paths by which the same method declaration is inherited from an interface. This fact causes no difficulty and never of itself results in a compile-time error.

- -

9.4.2 Overloading

- -If two methods of an interface (whether both declared in the same interface, or both inherited by an interface, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.

- -

9.4.3 Examples of Abstract Method Declarations

- -The following examples illustrate some (possibly subtle) points about abstract method declarations.

- -

9.4.3.1 Example: Overriding

- -Methods declared in interfaces are abstract and thus contain no implementation. About all that can be accomplished by an overriding method declaration, other than to affirm a method signature, is to restrict the exceptions that might be thrown by an implementation of the method. Here is a variation of the example shown in §8.4.3.1:

-

class BufferEmpty extends Exception {
-	BufferEmpty() { super(); }
-	BufferEmpty(String s) { super(s); }
-}
-class BufferError extends Exception {
-	BufferError() { super(); }
-	BufferError(String s) { super(s); }
-}
-public interface Buffer {
-	char get() throws BufferEmpty, BufferError;
-}
-public interface InfiniteBuffer extends Buffer {
-	 char get() throws BufferError;												// override
-}
-
-

9.4.3.2 Example: Overloading

- -In the example code:

-

interface PointInterface {
-	void move(int dx, int dy);
-}
-interface RealPointInterface extends PointInterface {
-	void move(float dx, float dy);
-	void move(double dx, double dy);
-}
-
-the method name move is overloaded in interface RealPointInterface with three different signatures, two of them declared and one inherited. Any non-abstract class that implements interface RealPointInterface must provide implementations of all three method signatures.

- -

9.5 Member Type Declarations

- -Interfaces may contain member type declarations (§8.5). A member type declaration in an interface is implicitly static and public.

- -If a member type declared with simple name C is directly enclosed within the declaration of an interface with fully qualified name N, then the member type has the fully qualified name N.C.

- -If the interface declares a member type with a certain name, then the declaration of that field is said to hide any and all accessible declarations of member types with the same name in superinterfaces of the interface.

- -An interface may inherit two or more type declarations with the same name. A compile-time error occurs on any attempt to refer to any ambiguously inherited class or interface by its simple name. If the same type declaration is inherited from an interface by multiple paths, the class or interface is considered to be inherited only once; it may be referred to by its simple name without ambiguity.

- - -


- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - - - - Arrays - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 10

- -

Arrays

-

- -In the Java programming language arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

- -An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

- -All the components of an array have the same type, called the component type of the array. If the component type of an array is T, then the type of the array itself is written T[].

- -The value of an array component of type float is always an element of the float value set (§4.2.3); similarly, the value of an array component of type double is always an element of the double value set. It is not permitted for the value of an array component of type float to be an element of the float-extended-exponent value set that is not also an element of the float value set, nor for the value of an array component of type double to be an element of the double-extended-exponent value set that is not also an element of the double value set.

- -The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the element type of the original array, and the components at this level of the data structure are called the elements of the original array.

- -There are some situations in which an element of an array can be an array: if the element type is Object or Cloneable or java.io.Serializable, then some or all of the elements may be arrays, because any array object can be assigned to any variable of these types. - -

10.1 Array Types

- -An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. The number of bracket pairs indicates the depth of array nesting. An array's length is not part of its type.

- -The element type of an array may be any type, whether primitive or reference. In particular:

-

-Array types are used in declarations and in cast expressions (§15.16).

- -

10.2 Array Variables

- -A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array. However, the initializer part of a declarator (§8.3) may create an array, a reference to which then becomes the initial value of the variable.

- -Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.

- -Here are examples of declarations of array variables that do not create arrays: -

-int[] ai;		// array of int
-short[][] as;		// array of array of short
-Object[]    ao,		// array of Object
-	otherAo;	// array of Object
-short	s,		// scalar short 
-	aas[][];	// array of array of short
-
-Here are some examples of declarations of array variables that create array objects:

-

-Exception ae[] = new Exception[3]; 
-Object aao[][] = new Exception[2][3];
-int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
-char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
-				 'S', 't', 'r', 'i', 'n', 'g' }; 
-String[] aas = { "array", "of", "String", };
-
-The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

-

byte[] rowvector, colvector, matrix[];
-
-This declaration is equivalent to:

-

byte rowvector[], colvector[], matrix[][];
-
-Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

- -If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A. This may result in a run-time exception on a later assignment; see §10.10 for a discussion.

- -

10.3 Array Creation

- -An array is created by an array creation expression (§15.10) or an array initializer (§10.6).

- -An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable length.

- -An array initializer creates an array and provides initial values for all its components.

- -

10.4 Array Access

- -A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i]. All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.

- -Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values. An attempt to access an array component with a long index value results in a compile-time error.

- -All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.

- -

10.5 Arrays: A Simple Example

- -The example:

-

class Gauss {
-	public static void main(String[] args) {
-		int[] ia = new int[101];
-		for (int i = 0; i < ia.length; i++)
-			ia[i] = i;
-		int sum = 0;
-		for (int i = 0; i < ia.length; i++)
-			sum += ia[i];
-		System.out.println(sum);
-	}
-}
-
-that produces the output:

-

5050
-
-declares a variable ia that has type array of int, that is, int[]. The variable ia is initialized to reference a newly created array object, created by an array creation expression (§15.10). The array creation expression specifies that the array should have 101 components. The length of the array is available using the field length, as shown.

- -The example program fills the array with the integers from 0 to 100, sums these integers, and prints the result. - -

10.6 Array Initializers

- -An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values:

-

-The following is repeated from §8.3 to make the presentation here clearer:

-

-An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".

- -The length of the constructed array will equal the number of expressions.

- -The expressions in an array initializer are executed from left to right in the textual order they occur in the source code. The nth variable initializer specifies the value of the n-1st array component. Each expression must be assignment-compatible (§5.2) with the array's component type, or a compile-time error results.

- -If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.

- -A trailing comma may appear after the last expression in an array initializer and is ignored.

- -As an example: -

class Test {
-	public static void main(String[] args) {
-		int ia[][] = { {1, 2}, null };
-		for (int i = 0; i < 2; i++)
-			for (int j = 0; j < 2; j++)
-				System.out.println(ia[i][j]);
-	}
-}
-
-prints:

-

1
-2
-
-before causing a NullPointerException in trying to index the second component of the array ia, which is a null reference.

- -

10.7 Array Members

- -The members of an array type are all of the following:

-

-

- -An array thus has the same public fields and methods as the following class:

-

class A implements Cloneable, java.io.Serializable {
-	public final int length = X;
-	public Object clone() {
-		try {
-			return super.clone();
-		} catch (CloneNotSupportedException e) {
-			throw new InternalError(e.getMessage());
-		}
-	}
-}
-
-Every array implements the interfaces Cloneable and java.io.Serializable.

- -That arrays are cloneable is shown by the test program: -

class Test {
-	public static void main(String[] args) {
-		int ia1[] = { 1, 2 };
-		int ia2[] = (int[])ia1.clone();
-		System.out.print((ia1 == ia2) + " ");
-		ia1[1]++;
-		System.out.println(ia2[1]);
-	}
-}
-
-which prints:

-

false 2
-
-showing that the components of the arrays referenced by ia1 and ia2 are different variables. (In some early implementations of the Java programming language this example failed to compile because the compiler incorrectly believed that the clone method for an array could throw a CloneNotSupportedException.)

- -A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

- -This is shown by the example program: -

class Test {
-	public static void main(String[] args) throws Throwable {
-		int ia[][] = { { 1 , 2}, null };
-		int ja[][] = (int[][])ia.clone();
-		System.out.print((ia == ja) + " ");
-		System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
-	}
-}
-
-which prints:

-

false true
-
-showing that the int[] array that is ia[0] and the int[] array that is ja[0] are the same array.

- -

10.8 Class Objects for Arrays

- -Every array has an associated Class object, shared with all other arrays with the same component type. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable.

- -This is shown by the following example code: -

class Test {
-	public static void main(String[] args) {
-		int[] ia = new int[3];
-		System.out.println(ia.getClass());
-		System.out.println(ia.getClass().getSuperclass());
-	}
-}
-
-which prints:

-

class [I
-class java.lang.Object
-
-where the string "[I" is the run-time type signature for the class object "array with component type int".

- -

10.9 An Array of Characters is Not a String

- -In Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).

- -A String object is immutable, that is, its contents never change, while an array of char has mutable elements. The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters.

- -

10.10 Array Store Exception

- -If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A.

- -Thus, the example: -

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint[] cpa = new ColoredPoint[10];
-		Point[] pa = cpa;
-		System.out.println(pa[1] == null);
-		try {
-			pa[0] = new Point();
-		} catch (ArrayStoreException e) {
-			System.out.println(e);
-		}
-	}
-}
-
-produces the output:

-

true
-java.lang.ArrayStoreException
-
-Here the variable pa has type Point[] and the variable cpa has as its value a reference to an object of type ColoredPoint[]. A ColoredPoint can be assigned to a Point; therefore, the value of cpa can be assigned to pa.

- -A reference to this array pa, for example, testing whether pa[1] is null, will not result in a run-time type error. This is because the element of the array of type ColoredPoint[] is a ColoredPoint, and every ColoredPoint can stand in for a Point, since Point is the superclass of ColoredPoint. -

- -On the other hand, an assignment to the array pa can result in a run-time error. At compile time, an assignment to an element of pa is checked to make sure that the value assigned is a Point. But since pa holds a reference to an array of ColoredPoint, the assignment is valid only if the type of the value assigned at run-time is, more specifically, a ColoredPoint. - -

-The Java virtual machine checks for such a situation at run-time to ensure that the assignment is valid; if not, an ArrayStoreException is thrown. More formally: an assignment to an element of an array whose type is A[], where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A. - -

- - -


- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - - - - Blocks and Statements - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 14

- -

Blocks and Statements

-

- -The sequence of execution of a program is controlled by statements, which are executed for their effect and do not have values.

- -Some statements contain other statements as part of their structure; such other statements are substatements of the statement. We say that statement S immediately contains statement U if there is no statement T different from S and U such that S contains T and T contains U. In the same manner, some statements contain expressions (§15) as part of their structure.

- -The first section of this chapter discusses the distinction between normal and abrupt completion of statements (§14.1). Most of the remaining sections explain the various kinds of statements, describing in detail both their normal behavior and any special treatment of abrupt completion.

- -Blocks are explained first (§14.2), followed by local class declarations (§14.3) and local variable declaration statements (§14.4).

- -Next a grammatical maneuver that sidesteps the familiar "dangling else" problem (§14.5) is explained.

- -Statements that will be familiar to C and C++ programmers are the empty (§14.6), labeled (§14.7), expression (§14.8), if (§14.9), switch (§14.10), while (§14.11), do (§14.12), for (§14.13), break (§14.14), continue (§14.15), and return (§14.16) statements.

- -Unlike C and C++, the Java programming language has no goto statement. However, the break and continue statements are allowed to mention statement labels.

- -The Java programming language statements that are not in the C language are the throw (§14.17), synchronized (§14.18), and try (§14.19) statements.

- -The last section (§14.20) of this chapter addresses the requirement that every statement be reachable in a certain technical sense.

- -

14.1 Normal and Abrupt Completion of Statements

- -Every statement has a normal mode of execution in which certain computational steps are carried out. The following sections describe the normal mode of execution for each kind of statement.

- -If all the steps are carried out as described, with no indication of abrupt completion, the statement is said to complete normally. However, certain events may prevent a statement from completing normally:

-

-If such an event occurs, then execution of one or more statements may be terminated before all steps of their normal mode of execution have completed; such statements are said to complete abruptly.

- -An abrupt completion always has an associated reason, which is one of the following:

-

-The terms "complete normally" and "complete abruptly" also apply to the evaluation of expressions (§15.6). The only reason an expression can complete abruptly is that an exception is thrown, because of either a throw with a given value (§14.17) or a run-time exception or error (§11, §15.6).

- -If a statement evaluates an expression, abrupt completion of the expression always causes the immediate abrupt completion of the statement, with the same reason. All succeeding steps in the normal mode of execution are not performed.

- -Unless otherwise specified in this chapter, abrupt completion of a substatement causes the immediate abrupt completion of the statement itself, with the same reason, and all succeeding steps in the normal mode of execution of the statement are not performed.

- -Unless otherwise specified, a statement completes normally if all expressions it evaluates and all substatements it executes complete normally.

- -

14.2 Blocks

- -A block is a sequence of statements, local class declarations and local variable declaration statements within braces.

-

-A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.

- -

14.3 Local Class Declarations

- -A local class is a nested class (§8) that is not a member of any class and that has a name. All local classes are inner classes (§8.1.2). Every local class declaration statement is immediately contained by a block. Local class declaration statements may be intermixed freely with other kinds of statements in the block.

- -The scope of a local class declared in a block is the rest of the immediately enclosing block, including its own class declaration.

- -The name of a local class C may not be redeclared as a local class of the directly enclosing method, constructor, or initializer block within the scope of C, or a compile-time error occurs. However, a local class declaration may be shadowed (§6.3.1) anywhere inside a class declaration nested within the local class declaration's scope. A local class does not have a canonical name, nor does it have a fully qualified name.

- -It is a compile-time error if a local class declaration contains any one of the following access modifiers: public, protected, private, or static.

- -Here is an example that illustrates several aspects of the rules given above:

-

class Global {
-	class Cyclic {}
-	void foo() {
-		new Cyclic(); // create a Global.Cyclic
-		class Cyclic extends Cyclic{}; // circular definition
-		{
-			class Local{};
-			{
-				class Local{}; // compile-time error
-			}
-			class Local{}; // compile-time error
-			class AnotherLocal {
-				void bar() {
-					class Local {}; // ok
-				}
-			}
-		}
-		class Local{}; // ok, not in scope of prior Local
-}
-
-The first statement of method foo creates an instance of the member class Global.Cyclic rather than an instance of the local class Cyclic, because the local class declaration is not yet in scope.

- -The fact that the scope of a local class encompasses its own declaration (not only its body) means that the definition of the local class Cyclic is indeed cyclic because it extends itself rather than Global.Cyclic. Consequently, the declaration of the local class Cyclic will be rejected at compile time.

- -Since local class names cannot be redeclared within the same method (or constructor or initializer, as the case may be), the second and third declarations of Local result in compile-time errors. However, Local can be redeclared in the context of another, more deeply nested, class such as AnotherLocal.

- -The fourth and last declaration of Local is legal, since it occurs outside the scope of any prior declaration of Local.

- -

14.4 Local Variable Declaration Statements

- -A local variable declaration statement declares one or more local variable names.

-

-The following are repeated from §8.3 to make the presentation here clearer:

-

-Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.

- -A local variable declaration can also appear in the header of a for statement (§14.13). In this case it is executed in the same manner as if it were part of a local variable declaration statement.

- -

14.4.1 Local Variable Declarators and Types

- -Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator.

- -If the optional keyword final appears at the start of the declarator, the variable being declared is a final variable(§4.5.4).

- -The type of the variable is denoted by the Type that appears in the local variable declaration, followed by any bracket pairs that follow the Identifier in the declarator.

- -Thus, the local variable declaration:

-

int a, b[], c[][];
-
-is equivalent to the series of declarations:

-

int a;
-int[] b;
-int[][] c;
-
-Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rule, however, also means that the local variable declaration:

-

float[][] f[][], g[][][], h[];													// Yechh!
-
-is equivalent to the series of declarations:

-

float[][][][] f;
-float[][][][][] g;
-float[][][] h;
-
-We do not recommend such "mixed notation" for array declarations.

- -A local variable of type float always contains a value that is an element of the float value set (§4.2.3); similarly, a local variable of type double always contains a value that is an element of the double value set. It is not permitted for a local variable of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a local variable of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.

- -

14.4.2 Scope of Local Variable Declarations

- -The scope of a local variable declaration in a block (§14.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

- -The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. The name of a local variable v may not be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. However, a local variable of a method or initializer block may be shadowed (§6.3.1) anywhere inside a class declaration nested within the scope of the local variable.

- -A local variable cannot be referred to using a qualified name (§6.6), only a simple name.

- -The example:

-

class Test {
-	static int x;
-	public static void main(String[] args) {
-		int x = x;
-	}
-}
-
-causes a compile-time error because the initialization of x is within the scope of the declaration of x as a local variable, and the local x does not yet have a value and cannot be used.

- -The following program does compile:

-

class Test {
-	static int x;
-	public static void main(String[] args) {
-		int x = (x=2)*2;
-		System.out.println(x);
-	}
-}
-
-because the local variable x is definitely assigned (§16) before it is used. It prints:

-

4
-
-Here is another example:

-class Test { - public static void main(String[] args) { - System.out.print("2+1="); - int two = 2, three = two + 1; - System.out.println(three); - } -} -

-which compiles correctly and produces the output:

-

2+1=3
-
-The initializer for three can correctly refer to the variable two declared in an earlier declarator, and the method invocation in the next line can correctly refer to the variable three declared earlier in the block.

- -The scope of a local variable declared in a for statement is the rest of the for statement, including its own initializer.

- -If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.

- -Thus the following example does not compile:

-

class Test {
-	public static void main(String[] args) {
-		int i;
-		for (int i = 0; i < 10; i++)
-			System.out.println(i);
-	}
-}
-
- -This restriction helps to detect some otherwise very obscure bugs. A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well. Hence, the following example compiles without error:

-

-class Test {
-	public static void main(String[] args) {
-		int i;
-		class Local {
-			{
-				for (int i = 0; i < 10; i++)
-				System.out.println(i);
-			}
-		}
-		new Local();
-	}
-}
-
- -On the other hand, local variables with the same name may be declared in two separate blocks or for statements neither of which contains the other. Thus:

-

-class Test {
-	public static void main(String[] args) {
-		for (int i = 0; i < 10; i++)
-			System.out.print(i + " ");
-		for (int i = 10; i > 0; i--)
-			System.out.print(i + " ");
-		System.out.println();
-	}
-}
-
-compiles without error and, when executed, produces the output:

-

0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
-
-

14.4.3 Shadowing of Names by Local Variables

- -If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable. Similarly, if a name is already declared as a variable or parameter name, then that outer declaration is shadowed throughout the scope of the local variable (provided that the shadowing does not cause a compile-time error under the rules of §14.4.2). The shadowed name can sometimes be accessed using an appropriately qualified name.

- -For example, the keyword this can be used to access a shadowed field x, using the form this.x. Indeed, this idiom typically appears in constructors (§8.8):

-

class Pair {
-	Object first, second;
-	public Pair(Object first, Object second) {
-		this.first = first;
-		this.second = second;
-	}
-}
-
-In this example, the constructor takes parameters having the same names as the fields to be initialized. This is simpler than having to invent different names for the parameters and is not too confusing in this stylized context. In general, however, it is considered poor style to have local variables with the same names as fields.

- -

14.4.4 Execution of Local Variable Declarations

- -A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable. If a declarator does not have an initialization expression, then a Java compiler must prove, using exactly the algorithm given in §16, that every reference to the variable is necessarily preceded by execution of an assignment to the variable. If this is not the case, then a compile-time error occurs.

- -Each initialization (except the first) is executed only if the evaluation of the preceding initialization expression completes normally. Execution of the local variable declaration completes normally only if evaluation of the last initialization expression completes normally; if the local variable declaration contains no initialization expressions, then executing it always completes normally.

- -

14.5 Statements

- -There are many kinds of statements in the Java programming language. Most correspond to statements in the C and C++ languages, but some are unique.

- -As in C and C++, the if statement of the Java programming language suffers from the so-called "dangling else problem," illustrated by this misleadingly formatted example:

-


-if (door.isOpen())
-	if (resident.isVisible())
-		resident.greet("Hello!");
-else door.bell.ring();	// A "dangling else"
-
-The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement. The Java programming language, like C and C++ and many programming languages before them, arbitrarily decree that an else clause belongs to the innermost if to which it might possibly belong. This rule is captured by the following grammar:

-

-The following are repeated from §14.9 to make the presentation here clearer:

-

-Statements are thus grammatically divided into two categories: those that might end in an if statement that has no else clause (a "short if statement") and those that definitely do not. Only statements that definitely do not end in a short if statement may appear as an immediate substatement before the keyword else in an if statement that does have an else clause.

- -This simple rule prevents the "dangling else" problem. The execution behavior of a statement with the "no short if" restriction is identical to the execution behavior of the same kind of statement without the "no short if" restriction; the distinction is drawn purely to resolve the syntactic difficulty.

- -

14.6 The Empty Statement

- -An empty statement does nothing.

-

-Execution of an empty statement always completes normally.

- -

14.7 Labeled Statements

- -Statements may have label prefixes.

-

-The Identifier is declared to be the label of the immediately contained Statement.

- -Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.14) or continue (§14.15) statements appearing anywhere within the labeled statement.

- -The scope of a label declared by a labeled statement is the statement immediately enclosed by the labeled statement.

- - Let l be a label, and let m be the immediately enclosing method, constructor, instance initializer or static initializer. It is a compile-time error if l shadows (§6.3.1) the declaration of another label immediately enclosed in m.

- -There is no restriction against using the same identifier as a label and as the name of a package, class, interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not obscure (§6.3.2) a package, class, interface, method, field, parameter, or local variable with the same name. Use of an identifier as a class, interface, method, field, local variable or as the parameter of an exception handler (§14.19) does not obscure a statement label with the same name.

- -A labeled statement is executed by executing the immediately contained Statement. If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason.

- -

14.8 Expression Statements

- -Certain kinds of expressions may be used as statements by following them with semicolons:

-

-An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.

- -Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements. Note that the Java programming language does not allow a "cast to void"-void is not a type-so the traditional C trick of writing an expression statement such as:

-

(void) ... ;			// incorrect!
-
-does not work. On the other hand, the language allows all the most useful kinds of expressions in expressions statements, and it does not require a method invocation used as an expression statement to invoke a void method, so such a trick is almost never needed. If a trick is needed, either an assignment statement (§15.26) or a local variable declaration statement (§14.4) can be used instead.

- -

14.9 The if Statement

- -The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.

-

-The Expression must have type boolean, or a compile-time error occurs.

- -

14.9.1 The if-then Statement

- -An if-then statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the if-then statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

-

-

14.9.2 The if-then-else Statement

- -An if-then-else statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, then the if-then-else statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

-

-

14.10 The switch Statement

- -The switch statement transfers control to one of several statements depending on the value of an expression.

-

-The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.

- -The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.28) in the case labels.

- -All of the following must be true, or a compile-time error will result:

-

for (i = 0; i < n; ++i) foo();
-
-where n is known to be positive. A trick known as Duff's device can be used in C or C++ to unroll the loop, but this is not valid code in the Java programming language:

-

int q = (n+7)/8;
-switch (n%8) {
-case 0:		do {	foo();		// Great C hack, Tom,
-case 7:			foo();		// but it's not valid here.
-case 6:			foo();
-case 5:			foo();
-case 4:			foo();
-case 3:			foo();
-case 2:			foo();
-case 1:			foo();
-		} while (--q >= 0);
-}
-
-Fortunately, this trick does not seem to be widely known or used. Moreover, it is less needed nowadays; this sort of code transformation is properly in the province of state-of-the-art optimizing compilers.

- -When the switch statement is executed, first the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the switch statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the Expression with each case constant. Then there is a choice:

-

-If any statement immediately contained by the Block body of the switch statement completes abruptly, it is handled as follows:

-

-As in C and C++, execution of statements in a switch block "falls through labels."

- -For example, the program:

-

class Toomany {
-	static void howMany(int k) {
-		switch (k) {
-		case 1:			System.out.print("one ");
-		case 2:			System.out.print("too ");
-		case 3:			System.out.println("many");
-		}
-	}
-	public static void main(String[] args) {
-		howMany(3);
-		howMany(2);
-		howMany(1);
-	}
-}
-
-contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints:

-

many
-too many
-one too many
-
-If code is not to fall through case to case in this manner, then break statements should be used, as in this example:

-

class Twomany {
-	static void howMany(int k) {
-		switch (k) {
-		case 1:			System.out.println("one");
-					break;					// exit the switch
-		case 2:			System.out.println("two");
-					break;					// exit the switch
-		case 3:			System.out.println("many");
-					break;					// not needed, but good style
-		}
-	}
-	public static void main(String[] args) {
-		howMany(1);
-		howMany(2);
-		howMany(3);
-	}
-}
-
-This program prints:

-

one
-two
-many
-
-

14.11 The while Statement

- -The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false.

-

-The Expression must have type boolean, or a compile-time error occurs.

- -A while statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the while statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

-

-If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.

- -

14.11.1 Abrupt Completion

- -Abrupt completion of the contained Statement is handled in the following manner:

-

-

14.12 The do Statement

- -The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false.

-

-The Expression must have type boolean, or a compile-time error occurs.

- -A do statement is executed by first executing the Statement. Then there is a choice:

-

-Executing a do statement always executes the contained Statement at least once.

- -

14.12.1 Abrupt Completion

- -Abrupt completion of the contained Statement is handled in the following manner:

-

-

14.12.2 Example of do statement

- -The following code is one possible implementation of the toHexString method of class Integer:

-

public static String toHexString(int i) {
-	StringBuffer buf = new StringBuffer(8);
-	do {
-		buf.append(Character.forDigit(i & 0xF, 16));
-		i >>>= 4;
-	} while (i != 0);
-	return buf.reverse().toString();
-}
-
-Because at least one digit must be generated, the do statement is an appropriate control structure.

- -

14.13 The for Statement

- -The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

-

-The Expression must have type boolean, or a compile-time error occurs.

- -

14.13.1 Initialization of for statement

- -A for statement is executed by first executing the ForInit code:

-

-If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement (§14.4) appearing in a block. The scope of a local variable declared in the ForInit part of a for statement (§14.13) includes all of the following:

-

-If execution of the local variable declaration completes abruptly for any reason, the for statement completes abruptly for the same reason.

-

-

14.13.2 Iteration of for statement

- -Next, a for iteration step is performed, as follows:

-

-If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.

- -If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement.

- -

14.13.3 Abrupt Completion of for statement

- -Abrupt completion of the contained Statement is handled in the following manner:

-

-

14.14 The break Statement

- -A break statement transfers control out of an enclosing statement.

-

-A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement of the immediately enclosing method or initializer block; this statement, which is called the break target, then immediately completes normally.

- -To be precise, a break statement with no label always completes abruptly, the reason being a break with no label. If no switch, while, do, or for statement encloses the break statement, a compile-time error occurs.

- -A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a while, do, for, or switch statement. A break statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps.

- -To be precise, a break statement with label Identifier always completes abruptly, the reason being a break with label Identifier. If no labeled statement with Identifier as its label encloses the break statement, a compile-time error occurs.

- -It can be seen, then, that a break statement always completes abruptly.

- -The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.19) within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break statement.

- -In the following example, a mathematical graph is represented by an array of arrays. A graph consists of a set of nodes and a set of edges; each edge is an arrow that points from some node to some other node, or from a node to itself. In this example it is assumed that there are no redundant edges; that is, for any two nodes P and Q, where Q may be the same as P, there is at most one edge from P to Q. Nodes are represented by integers, and there is an edge from node i to node edges[i][j] for every i and j for which the array reference edges[i][j] does not throw an IndexOutOfBoundsException.

- -The task of the method loseEdges, given integers i and j, is to construct a new graph by copying a given graph but omitting the edge from node i to node j, if any, and the edge from node j to node i, if any:

-

class Graph {
-	int edges[][];
-	public Graph(int[][] edges) { this.edges = edges; }
-	public Graph loseEdges(int i, int j) {
-		int n = edges.length;
-		int[][] newedges = new int[n][];
-		for (int k = 0; k < n; ++k) {
-			edgelist: {
-				int z;
-				search: {
-					if (k == i) {
-						for (z = 0; z < edges[k].length; ++z)
-							if (edges[k][z] == j)
-								break search;
-					} else if (k == j) {
-						for (z = 0; z < edges[k].length; ++z)
-							if (edges[k][z] == i)
-								break search;
-					}
-					// No edge to be deleted; share this list.
-					newedges[k] = edges[k];
-					break edgelist;
-				} //search
-				// Copy the list, omitting the edge at position z.
-				int m = edges[k].length - 1;
-				int ne[] = new int[m];
-				System.arraycopy(edges[k], 0, ne, 0, z);
-				System.arraycopy(edges[k], z+1, ne, z, m-z);
-				newedges[k] = ne;
-			} //edgelist
-		}
-		return new Graph(newedges);
-	}
-}
-
-Note the use of two statement labels, edgelist and search, and the use of break statements. This allows the code that copies a list, omitting one edge, to be shared between two separate tests, the test for an edge from node i to node j, and the test for an edge from node j to node i.

- -

14.15 The continue Statement

- -A continue statement may occur only in a while, do, or for statement; statements of these three kinds are called iteration statements. Control passes to the loop-continuation point of an iteration statement.

-

-A continue statement with no label attempts to transfer control to the innermost enclosing while, do, or for statement of the immediately enclosing method or initializer block; this statement, which is called the continue target, then immediately ends the current iteration and begins a new one.

- -To be precise, such a continue statement always completes abruptly, the reason being a continue with no label. If no while, do, or for statement of the immediately enclosing method or initializer block encloses the continue statement, a compile-time error occurs.

- -A continue statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; that statement, which is called the continue target, then immediately ends the current iteration and begins a new one. The continue target must be a while, do, or for statement or a compile-time error occurs. A continue statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps.

- -More precisely, a continue statement with label Identifier always completes abruptly, the reason being a continue with label Identifier. If no labeled statement with Identifier as its label contains the continue statement, a compile-time error occurs.

- -It can be seen, then, that a continue statement always completes abruptly.

- -See the descriptions of the while statement (§14.11), do statement (§14.12), and for statement (§14.13) for a discussion of the handling of abrupt termination because of continue.

- -The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.19) within the continue target whose try blocks contain the continue statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the continue target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a continue statement.

- -In the Graph example in the preceding section, one of the break statements is used to finish execution of the entire body of the outermost for loop. This break can be replaced by a continue if the for loop itself is labeled:

-

class Graph {
-	. . .
-	public Graph loseEdges(int i, int j) {
-		int n = edges.length;
-		int[][] newedges = new int[n][];
-		edgelists: for (int k = 0; k < n; ++k) {
-			int z;
-			search: {
-				if (k == i) {
-					. . .
-				} else if (k == j) {
-					. . .
-				}
-				newedges[k] = edges[k];
-				continue edgelists;
-			} // search
-			. . .
-		} // edgelists
-		return new Graph(newedges);
-	}
-}
-
-Which to use, if either, is largely a matter of programming style.

- -

14.16 The return Statement

- -A return statement returns control to the invoker of a method (§8.4, §15.12) or constructor (§8.8, §15.9).

-

-A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.8). A compile-time error occurs if a return statement appears within an instance initializer or a static initializer (§8.7). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it.

- -To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.

- -A return statement with an Expression must be contained in a method declaration that is declared to return a value (§8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (§5.2) to the declared result type of the method, or a compile-time error occurs.

- -A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V. If the expression is of type float and is not FP-strict (§15.4), then the value may be an element of either the float value set or the float-extended-exponent value set (§4.2.3). If the expression is of type double and is not FP-strict, then the value may be an element of either the double value set or the double-extended-exponent value set.

- -It can be seen, then, that a return statement always completes abruptly.

- -The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.19) within the method or constructor whose try blocks contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

- -

14.17 The throw Statement

- -A throw statement causes an exception (§11) to be thrown. The result is an immediate transfer of control (§11.3) that may exit multiple statements and multiple constructor, instance initializer, static initializer and field initializer evaluations, and method invocations until a try statement (§14.19) is found that catches the thrown value. If no such try statement is found, then execution of the thread (§17) that executed the throw is terminated (§11.3) after invocation of the uncaughtException method for the thread group to which the thread belongs.

-

-The Expression in a throw statement must denote a variable or value of a reference type which is assignable (§5.2) to the type Throwable, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs:

-

-A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null value V, then the throw statement completes abruptly, the reason being a throw with value V. If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null. The throw statement then completes abruptly, the reason being a throw with value V'.

- -It can be seen, then, that a throw statement always completes abruptly.

- -If there are any enclosing try statements (§14.19) whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.

- -If a throw statement is contained in a method declaration, but its value is not caught by some try statement that contains it, then the invocation of the method completes abruptly because of the throw.

- -If a throw statement is contained in a constructor declaration, but its value is not caught by some try statement that contains it, then the class instance creation expression that invoked the constructor will complete abruptly because of the throw.

- -If a throw statement is contained in a static initializer (§8.7), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it. If at run-time, despite this check, the value is not caught by some try statement that contains the throw statement, then the value is rethrown if it is an instance of class Error or one of its subclasses; otherwise, it is wrapped in an ExceptionInInitializerError object, which is then thrown (§12.4.2).

- -If a throw statement is contained in an instance initializer (§8.6), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it, or the type of the thrown exception (or one of its superclasses) occurs in the throws clause of every constructor of the class.

- -By convention, user-declared throwable types should usually be declared to be subclasses of class Exception, which is a subclass of class Throwable (§11.5).

- -

14.18 The synchronized Statement

- -A synchronized statement acquires a mutual-exclusion lock (§17.13) on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock.

-

-The type of Expression must be a reference type, or a compile-time error occurs.

- -A synchronized statement is executed by first evaluating the Expression.

- -If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.

- -Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

- -Otherwise, let the non-null value of the Expression be V. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason.

- -Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.

- -The locks acquired by synchronized statements are the same as the locks that are acquired implicitly by synchronized methods; see §8.4.3.6. A single thread may hold a lock more than once.

- -The example:

-

class Test {
-	public static void main(String[] args) {
-		Test t = new Test();
-		synchronized(t) {
-			synchronized(t) {
-				System.out.println("made it!");
-			}
-		}
-	}
-}
-
-prints:

-

made it!
-
-This example would deadlock if a single thread were not permitted to lock a lock more than once.

- -

14.19 The try statement

- -A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If the try statement has a finally clause, then another block of code is executed, no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.

-

-The following is repeated from §8.4.1 to make the presentation here clearer:

-

-The following is repeated from §8.3 to make the presentation here clearer:

-

-The Block immediately after the keyword try is called the try block of the try statement. The Block immediately after the keyword finally is called the finally block of the try statement.

- -A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass of Throwable, or a compile-time error occurs. The scope of the parameter variable is the Block of the catch clause.

- -An exception parameter of a catch clause must not have the same name as a local variable or parameter of the method or initializer block immediately enclosing the catch clause, or a compile-time error occurs.

- -The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (§14.19) is the entire block associated with the catch.

- -Within the Block of the catch clause, the name of the parameter may not be redeclared as a local variable of the directly enclosing method or initializer block, nor may it be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method or initializer block, or a compile-time error occurs. However, an exception parameter may be shadowed (§6.3.1) anywhere inside a class declaration nested within the Block of the catch clause.

- -It is a compile-time error if an exception parameter that is declared final is assigned to within the body of the catch clause.

- -Exception parameters cannot be referred to using qualified names (§6.6), only by simple names.

- -Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its actual argument the thrown exception object.

- -A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.

- -Handling of the finally block is rather complex, so the two cases of a try statement with and without a finally block are described separately.

- -

14.19.1 Execution of try-catch

- -A try statement without a finally block is executed by first executing the try block. Then there is a choice:

-

class BlewIt extends Exception {
-	BlewIt() { }
-	BlewIt(String s) { super(s); }
-}
-class Test {
-	static void blowUp() throws BlewIt { throw new BlewIt(); }
-	public static void main(String[] args) {
-		try {
-			blowUp();
-		} catch (RuntimeException r) {
-			System.out.println("RuntimeException:" + r);
-		} catch (BlewIt b) {
-			System.out.println("BlewIt");
-		}
-	}
-}
-
-the exception BlewIt is thrown by the method blowUp. The try-catch statement in the body of main has two catch clauses. The run-time type of the exception is BlewIt which is not assignable to a variable of type RuntimeException, but is assignable to a variable of type BlewIt, so the output of the example is:

-

BlewIt
-
-

14.19.2 Execution of try-catch-finally

- -A try statement with a finally block is executed by first executing the try block. Then there is a choice:

-

class BlewIt extends Exception {
-	BlewIt() { }
-	BlewIt(String s) { super(s); }
-}
-class Test {
-	static void blowUp() throws BlewIt {
-		throw new NullPointerException();
-	}
-	public static void main(String[] args) {
-		try {
-			blowUp();
-		} catch (BlewIt b) {
-			System.out.println("BlewIt");
-		} finally {
-			System.out.println("Uncaught Exception");
-		}
-	}
-}
-
-produces the output:

-

Uncaught Exception
-java.lang.NullPointerException
-	at Test.blowUp(Test.java:7)
-	at Test.main(Test.java:11)
-
-The NullPointerException (which is a kind of RuntimeException) that is thrown by method blowUp is not caught by the try statement in main, because a NullPointerException is not assignable to a variable of type BlewIt. This causes the finally clause to execute, after which the thread executing main, which is the only thread of the test program, terminates because of an uncaught exception, which typically results in printing the exception name and a simple backtrace.

- -

14.20 Unreachable Statements

- -It is a compile-time error if a statement cannot be executed because it is unreachable. Every Java compiler must carry out the conservative flow analysis specified here to make sure all statements are reachable.

- -This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

- -For example, a Java compiler will accept the code:

-

{
-	int n = 5;
-	while (n > 7) k = 2;
-}
-
-even though the value of n is known at compile time and in principle it can be known at compile time that the assignment to k can never be executed.

- -A Java compiler must operate according to the rules laid out in this section.

- -The rules in this section define two technical terms:

-

-The definitions here allow a statement to complete normally only if it is reachable.

- -To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."

- -The rules are as follows:

-

-The then-statement is reachable iff the if-then statement is reachable and the condition expression is not a constant expression whose value is false.

-

-The actual rules for the if statement are as follows:

-

while (false) { x=3; }
-
-because the statement x=3; is not reachable; but the superficially similar case:

-

if (false) { x=3; }
-
-does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

- -The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

-

static final boolean DEBUG = false;
-
-and then write code such as:

-

if (DEBUG) { x=3; }
-
-The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

- -This ability to "conditionally compile" has a significant impact on, and relationship to, binary compatibility (§13). If a set of classes that use such a "flag" variable are compiled and conditional code is omitted, it does not suffice later to distribute just a new version of the class or interface that contains the definition of the flag. A change to the value of a flag is, therefore, not binary compatible with preexisting binaries (§13.4.8). (There are other reasons for such incompatibility as well, such as the use of constants in case labels in switch statements; see §13.4.8.)

- - -


- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - - - - Expressions - - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-

- - -

-CHAPTER - 15

- -

Expressions

-

- -Much of the work in a program is done by evaluating expressions, either for their side effects, such as assignments to variables, or for their values, which can be used as arguments or operands in larger expressions, or to affect the execution sequence in statements, or both.

- -This chapter specifies the meanings of expressions and the rules for their evaluation.

- -

15.1 Evaluation, Denotation, and Result

- -When an expression in a program is evaluated (executed), the result denotes one of three things:

-

-Evaluation of an expression can also produce side effects, because expressions may contain embedded assignments, increment operators, decrement operators, and method invocations.

- -An expression denotes nothing if and only if it is a method invocation (§15.12) that invokes a method that does not return a value, that is, a method declared void (§8.4). Such an expression can be used only as an expression statement (§14.8), because every other context in which an expression can appear requires the expression to denote something. An expression statement that is a method invocation may also invoke a method that produces a result; in this case the value returned by the method is quietly discarded.

- -Value set conversion (§5.1.8) is applied to the result of every expression that produces a value.

- -Each expression occurs in the declaration of some (class or interface) type that is being declared: in a field initializer, in a static initializer, in a constructor declaration, or in the code for a method.

- -

15.2 Variables as Values

- -If an expression denotes a variable, and a value is required for use in further evaluation, then the value of that variable is used. In this context, if the expression denotes a variable or a value, we may speak simply of the value of the expression.

- -If the value of a variable of type float or double is used in this manner, then value set conversion (§5.1.8) is applied to the value of the variable.

- -

15.3 Type of an Expression

- -If an expression denotes a variable or a value, then the expression has a type known at compile time. The rules for determining the type of an expression are explained separately below for each kind of expression.

- -The value of an expression is always assignment compatible (§5.2) with the type of the expression, just as the value stored in a variable is always compatible with the type of the variable.

- -In other words, the value of an expression whose type is T is always suitable for assignment to a variable of type T.

- -Note that an expression whose type is a class type F that is declared final is guaranteed to have a value that is either a null reference or an object whose class is F itself, because final types have no subclasses.

- -

15.4 FP-strict Expressions

- -If the type of an expression is float or double, then there is a question as to what value set (§4.2.3) the value of the expression is drawn from. This is governed by the rules of value set conversion (§5.1.8); these rules in turn depend on whether or not the expression is FP-strict.

- -Every compile-time constant expression (§15.28) is FP-strict. If an expression is not a compile-time constant expression, then consider all the class declarations, interface declarations, and method declarations that contain the expression. If any such declaration bears the strictfp modifier, then the expression is FP-strict.

- -If a class, interface, or method, X, is declared strictfp, then X and any class, interface, method, constructor, instance initializer, static initializer or variable initializer within X is said to be FP-strict.

- -It follows that an expression is not FP-strict if and only if it is not a compile-time constant expression and it does not appear within any declaration that has the strictfp modifier.

- -Within an FP-strict expression, all intermediate values must be elements of the float value set or the double value set, implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats. Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow.

- -

15.5 Expressions and Run-Time Checks

- -If the type of an expression is a primitive type, then the value of the expression is of that same primitive type. But if the type of an expression is a reference type, then the class of the referenced object, or even whether the value is a reference to an object rather than null, is not necessarily known at compile time. There are a few places in the Java programming language where the actual class of a referenced object affects program execution in a manner that cannot be deduced from the type of the expression. They are as follows:

-

-The first two of the cases just listed ought never to result in detecting a type error. Thus, a run-time type error can occur only in these situations:

-

-

15.6 Normal and Abrupt Completion of Evaluation

- -Every expression has a normal mode of evaluation in which certain computational steps are carried out. The following sections describe the normal mode of evaluation for each kind of expression. If all the steps are carried out without an exception being thrown, the expression is said to complete normally.

- -If, however, evaluation of an expression throws an exception, then the expression is said to complete abruptly. An abrupt completion always has an associated reason, which is always a throw with a given value.

- -Run-time exceptions are thrown by the predefined operators as follows:

-

-A method invocation expression can also result in an exception being thrown if an exception occurs that causes execution of the method body to complete abruptly. A class instance creation expression can also result in an exception being thrown if an exception occurs that causes execution of the constructor to complete abruptly. Various linkage and virtual machine errors may also occur during the evaluation of an expression. By their nature, such errors are difficult to predict and difficult to handle.

- -If an exception occurs, then evaluation of one or more expressions may be terminated before all steps of their normal mode of evaluation are complete; such expressions are said to complete abruptly. The terms "complete normally" and "complete abruptly" are also applied to the execution of statements (§14.1). A statement may complete abruptly for a variety of reasons, not just because an exception is thrown.

- -If evaluation of an expression requires evaluation of a subexpression, abrupt completion of the subexpression always causes the immediate abrupt completion of the expression itself, with the same reason, and all succeeding steps in the normal mode of evaluation are not performed.

- -

15.7 Evaluation Order

- -The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

- -It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

- -

15.7.1 Evaluate Left-Hand Operand First

- -The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. For example, if the left-hand operand contains an assignment to a variable and the right-hand operand contains a reference to that same variable, then the value produced by the reference will reflect the fact that the assignment occurred first.

- -Thus:

-

class Test {
-	public static void main(String[] args) {
-		int i = 2;
-		int j = (i=3) * i;
-		System.out.println(j);
-	}
-}
-
-prints:

-

9
-
-It is not permitted for it to print 6 instead of 9.

- -If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied combining operation. So, for example, the test program:

-

class Test {
-	public static void main(String[] args) {
-		int a = 9;
-		a += (a = 3);									// first example
-		System.out.println(a);
-		int b = 9;
-		b = b + (b = 3);									// second example
-		System.out.println(b);
-	}
-}
-
-prints:

-

12
-12
-
-because the two assignment statements both fetch and remember the value of the left-hand operand, which is 9, before the right-hand operand of the addition is evaluated, thereby setting the variable to 3. It is not permitted for either example to produce the result 6. Note that both of these examples have unspecified behavior in C, according to the ANSI/ISO standard.

- -If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand appears to have been evaluated.

- -Thus, the test program:

-

class Test {
-	public static void main(String[] args) {
-		int j = 1;
-		try {
-			int i = forgetIt() / (j = 2);
-		} catch (Exception e) {
-			System.out.println(e);
-			System.out.println("Now j = " + j);
-		}
-	}
-	static int forgetIt() throws Exception {
-		throw new Exception("I'm outta here!");
-	}
-}
-
-prints:

-

java.lang.Exception: I'm outta here!
-Now j = 1
-
-That is, the left-hand operand forgetIt() of the operator / throws an exception before the right-hand operand is evaluated and its embedded assignment of 2 to j occurs.

- -

15.7.2 Evaluate Operands before Operation

- -The Java programming language also guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

- -If the binary operator is an integer division / (§15.17.2) or integer remainder % (§15.17.3), then its execution may raise an ArithmeticException, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.

- -So, for example, the program:

-

class Test {
-	public static void main(String[] args) {
-		int divisor = 0;
-		try {
-			int i = 1 / (divisor * loseBig());
-		} catch (Exception e) {
-			System.out.println(e);
-		}
-	}
-	static int loseBig() throws Exception {
-		throw new Exception("Shuffle off to Buffalo!");
-	}
-}
-
-always prints:

-

java.lang.Exception: Shuffle off to Buffalo!
-
-and not:

-

java.lang.ArithmeticException: / by zero
-
-since no part of the division operation, including signaling of a divide-by-zero exception, may appear to occur before the invocation of loseBig completes, even though the implementation may be able to detect or infer that the division operation would certainly result in a divide-by-zero exception.

- -

15.7.3 Evaluation Respects Parentheses and Precedence

- -Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence. An implementation may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects, even in the presence of multiple threads of execution (using the thread execution model in §17), for all possible computational values that might be involved.

- -In the case of floating-point calculations, this rule applies also for infinity and not-a-number (NaN) values. For example, !(x<y) may not be rewritten as x>=y, because these expressions have different values if either x or y is NaN or both are NaN.

- -Specifically, floating-point calculations that appear to be mathematically associative are unlikely to be computationally associative. Such computations must not be naively reordered.

- -For example, it is not correct for a Java compiler to rewrite 4.0*x*0.5 as 2.0*x; while roundoff happens not to be an issue here, there are large values of x for which the first expression produces infinity (because of overflow) but the second expression produces a finite result.

- -So, for example, the test program:

-

strictfp class Test {
-	public static void main(String[] args) {
-		double d = 8e+307;
-		System.out.println(4.0 * d * 0.5);
-		System.out.println(2.0 * d);
-	}
-}
-
-prints:

-

Infinity
-1.6e+308
-
-because the first expression overflows and the second does not.

- -In contrast, integer addition and multiplication are provably associative in the Java programming language.

- -For example a+b+c, where a, b, and c are local variables (this simplifying assumption avoids issues involving multiple threads and volatile variables), will always produce the same answer whether evaluated as (a+b)+c or a+(b+c); if the expression b+c occurs nearby in the code, a smart compiler may be able to use this common subexpression.

- -

15.7.4 Argument Lists are Evaluated Left-to-Right

- -In a method or constructor invocation or class instance creation expression, argument expressions may appear within the parentheses, separated by commas. Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

- -Thus:

-

class Test {
-	public static void main(String[] args) {
-		String s = "going, ";
-		print3(s, s, s = "gone");
-	}
-	static void print3(String a, String b, String c) {
-		System.out.println(a + b + c);
-	}
-}
-
-always prints:

-

going, going, gone
-
-because the assignment of the string "gone" to s occurs after the first two arguments to print3 have been evaluated.

- -If evaluation of an argument expression completes abruptly, no part of any argument expression to its right appears to have been evaluated.

- -Thus, the example:

-

class Test {
-	static int id;
-	public static void main(String[] args) {
-		try {
-			test(id = 1, oops(), id = 3);
-		} catch (Exception e) {
-			System.out.println(e + ", id=" + id);
-		}
-	}
-	static int oops() throws Exception {
-		throw new Exception("oops");
-	}
-	static int test(int a, int b, int c) {
-		return a + b + c;
-	}
-}
-
-prints:

-

java.lang.Exception: oops, id=1
-
-because the assignment of 3 to id is not executed.

- -

15.7.5 Evaluation Order for Other Expressions

- -The order of evaluation for some expressions is not completely covered by these general rules, because these expressions may raise exceptional conditions at times that must be specified. See, specifically, the detailed explanations of evaluation order for the following kinds of expressions:

-

-

15.8 Primary Expressions

- -Primary expressions include most of the simplest kinds of expressions, from which all others are constructed: literals, class literals, field accesses, method invocations, and array accesses. A parenthesized expression is also treated syntactically as a primary expression.

-

-

15.8.1 Lexical Literals

- -A literal (§3.10) denotes a fixed, unchanging value.

- -The following production from §3.10 is repeated here for convenience:

-

-The type of a literal is determined as follows:

-

-Evaluation of a lexical literal always completes normally.

- -

15.8.2 Class Literals

- -A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a `.' and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

- -

15.8.3 this

- -The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

- -When used as a primary expression, the keyword this denotes a value, that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.

- -In the example:

-

class IntVector {
-	int[] v;
-	boolean equals(IntVector other) {
-		if (this == other)
-			return true;
-		if (v.length != other.v.length)
-			return false;
-		for (int i = 0; i < v.length; i++)
-			if (v[i] != other.v[i])
-				return false;
-		return true;
-	}
-}
-
-the class IntVector implements a method equals, which compares two vectors. If the other vector is the same vector object as the one for which the equals method was invoked, then the check can skip the length and value comparisons. The equals method implements this check by comparing the reference to the other object to this.

- -The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body (§8.8.5).

- -

15.8.4 Qualified this

- -Any lexically enclosing instance can be referred to by explicitly qualifying the keyword this.

- -Let C be the class denoted by ClassName. Let n be an integer such that C is the nth lexically enclosing class of the class in which the qualified this expression appears. The value of an expression of the form ClassName.this is the nth lexically enclosing instance of this (§8.1.2). The type of the expression is C. It is a compile-time error if the current class is not an inner class of class C or C itself.

- -

15.8.5 Parenthesized Expressions

- -A parenthesized expression is a primary expression whose type is the type of the contained expression and whose value at run time is the value of the contained expression. If the contained expression denotes a variable then the parenthesized expression also denotes that variable.

- -Parentheses do not affect in any way the choice of value set (§4.2.3) for the value of an expression of type float or double.

- -

15.9 Class Instance Creation Expressions

- -A class instance creation expression is used to create new objects that are instances of classes.

-

-Class instance creation expressions have two forms:

-

-Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (§15.9.5) and creates an instance of it.

- -We say that a class is instantiated when an instance of the class is created by a class instance creation expression. Class instantiation involves determining what class is to be instantiated, what the enclosing instances (if any) of the newly created instance are, what constructor should be invoked to create the new instance and what arguments should be passed to that constructor.

- -

15.9.1 Determining the Class being Instantiated

- -If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:

-

-If a class instance creation expression does not declare an anonymous class, then:

-

-The type of the class instance creation expression is the class type being instantiated.

- -

15.9.2 Determining Enclosing Instances

- -Let C be the class being instantiated, and let i the instance being created. If C is an inner class then i may have an immediately enclosing instance. The immediately enclosing instance of i (§8.1.2) is determined as follows:

-

-In addition, if C is an anonymous class, and the direct superclass of C, S, is an inner class then i may have an immediately enclosing instance with respect to S which is determined as follows:

-

-

15.9.3 Choosing the Constructor and its Arguments

- -Let C be the class type being instantiated. To create an instance of C, i, a constructor of C is chosen at compile-time by the following rules:

-

-Note that the type of the class instance creation expression may be an anonymous class type, in which case the constructor being invoked is an anonymous constructor.

- -

15.9.4 Run-time Evaluation of Class Instance Creation Expressions

- -At run time, evaluation of a class instance creation expression is as follows.

- -First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null, a NullPointerException is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason.

- -Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (§15.9.6).

- -The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (§4.5.5).

- -Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.

- -Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.8) and is described in detail in §12.5.

- -The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.

- -

15.9.5 Anonymous Class Declarations

- -An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.

- -An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.2); it is never static (§8.1.1, §8.5.2). An anonymous class is always implicitly final (§8.1.1.2).

- -

15.9.5.1 Anonymous Constructors

- -An anonymous class cannot have an explicitly declared constructor. Instead, the compiler must automatically provide an anonymous constructor for the anonymous class. The form of the anonymous constructor of an anonymous class C with direct superclass S is as follows:

-

-In all cases, the throws clause of an anonymous constructor must list all the checked exceptions thrown by the explicit superclass constructor invocation statement contained within the anonymous constructor, and all checked exceptions thrown by any instance initializers or instance variable initializers of the anonymous class.

- -Note that it is possible for the signature of the anonymous constructor to refer to an inaccessible type (for example, if such a type occurred in the signature of the superclass constructor cs). This does not, in itself, cause any errors at either compile time or run time.

- -

15.9.6 Example: Evaluation Order and Out-of-Memory Detection

- -If evaluation of a class instance creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs before any argument expressions are evaluated.

- -So, for example, the test program:

-

class List {
-	int value;
-	List next;
-	static List head = new List(0);
-	List(int n) { value = n; next = head; head = this; }
-}
-class Test {
-	public static void main(String[] args) {
-		int id = 0, oldid = 0;
-		try {
-			for (;;) {
-				++id;
-				new List(oldid = id);
-			}
-		} catch (Error e) {
-			System.out.println(e + ", " + (oldid==id));
-		}
-	}
-}
-
-prints:

-

java.lang.OutOfMemoryError: List, false
-
-because the out-or-memory condition is detected before the argument expression oldid = id is evaluated.

- -Compare this to the treatment of array creation expressions (§15.10), for which the out-of-memory condition is detected after evaluation of the dimension expressions (§15.10.3).

- -

15.10 Array Creation Expressions

- -An array instance creation expression is used to create new arrays (§10).

-

-

-

-An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or TypeName. The TypeName may name any named reference type, even an abstract class type (§8.1.1.1) or an interface type (§9).

- -The type of the creation expression is an array type that can denoted by a copy of the creation expression from which the new keyword and every DimExpr expression and array initializer have been deleted.

- -For example, the type of the creation expression:

-

new double[3][3][]
-
-is:

-

double[][][]
-
-The type of each dimension expression within a DimExpr must be an integral type, or a compile-time error occurs. Each expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs; this means, specifically, that the type of a dimension expression must not be long.

- -If an array initializer is provided, the newly allocated array will be initialized with the values provided by the array initializer as described in §10.6.

- -

15.10.1 Run-time Evaluation of Array Creation Expressions

- -At run time, evaluation of an array creation expression behaves as follows. If there are no dimension expressions, then there must be an array initializer. The value of the array initializer is the value of the array creation expression. Otherwise:

- -First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.

- -Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then an NegativeArraySizeException is thrown.

- -Next, space is allocated for the new array. If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an OutOfMemoryError.

- -Then, if a single DimExpr appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.5.5).

- -If an array creation expression contains N DimExpr expressions, then it effectively executes a set of nested loops of depth N - 1 to create the implied arrays of arrays.

- -For example, the declaration:

-

float[][] matrix = new float[3][3];
-
-is equivalent in behavior to:

-

float[][] matrix = new float[3][];
-for (int d = 0; d < matrix.length; d++)
-	matrix[d] = new float[3];
-
-and:

-

Age[][][][][] Aquarius = new Age[6][10][8][12][];
-
-is equivalent to:

-

Age[][][][][] Aquarius = new Age[6][][][][];
-for (int d1 = 0; d1 < Aquarius.length; d1++) {
-	Aquarius[d1] = new Age[10][][][];
-	for (int d2 = 0; d2 < Aquarius[d1].length; d2++) {
-		Aquarius[d1][d2] = new Age[8][][];
-		for (int d3 = 0; d3 < Aquarius[d1][d2].length; d3++) {
-			Aquarius[d1][d2][d3] = new Age[12][];
-		}
-	}
-}
-
-with d, d1, d2 and d3 replaced by names that are not already locally declared. Thus, a single new expression actually creates one array of length 6, 6 arrays of length 10, 6 x 10 = 60 arrays of length 8, and 6 x 10 x 8 = 480 arrays of length 12. This example leaves the fifth dimension, which would be arrays containing the actual array elements (references to Age objects), initialized only to null references. These arrays can be filled in later by other code, such as:

-

Age[] Hair = { new Age("quartz"), new Age("topaz") };
-Aquarius[1][9][6][9] = Hair;
-
-A multidimensional array need not have arrays of the same length at each level. 

- -Thus, a triangular matrix may be created by:

-float triang[][] = new float[100][]; -for (int i = 0; i < triang.length; i++) - triang[i] = new float[i+1]; -

-

15.10.2 Example: Array Creation Evaluation Order

- -In an array creation expression (§15.10), there may be one or more dimension expressions, each within brackets. Each dimension expression is fully evaluated before any part of any dimension expression to its right.

- -Thus:

-

class Test {
-	public static void main(String[] args) {
-		int i = 4;
-		int ia[][] = new int[i][i=3];
-		System.out.println(
-			"[" + ia.length + "," + ia[0].length + "]");
-	}
-}
-
-prints:

-

[4,3]
-
-because the first dimension is calculated as 4 before the second dimension expression sets i to 3.

- -If evaluation of a dimension expression completes abruptly, no part of any dimension expression to its right will appear to have been evaluated. Thus, the example:

-

class Test {
-	public static void main(String[] args) {
-		int[][] a = { { 00, 01 }, { 10, 11 } };
-		int i = 99;
-		try {
-			a[val()][i = 1]++;
-		} catch (Exception e) {
-			System.out.println(e + ", i=" + i);
-		}
-	}
-	static int val() throws Exception {
-		throw new Exception("unimplemented");
-	}
-}
-
-prints:

-

java.lang.Exception: unimplemented, i=99
-
-because the embedded assignment that sets i to 1 is never executed.

- -

15.10.3 Example: Array Creation and Out-of-Memory Detection

- -If evaluation of an array creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs only after evaluation of all dimension expressions has completed normally.

- -So, for example, the test program:

-

class Test {
-	public static void main(String[] args) {
-		int len = 0, oldlen = 0;
-		Object[] a = new Object[0];
-		try {
-			for (;;) {
-				++len;
-				Object[] temp = new Object[oldlen = len];
-				temp[0] = a;
-				a = temp;
-			}
-		} catch (Error e) {
-			System.out.println(e + ", " + (oldlen==len));
-		}
-	}
-}
-
-prints:

-

java.lang.OutOfMemoryError, true
-
-because the out-of-memory condition is detected after the dimension expression oldlen = len is evaluated.

- -Compare this to class instance creation expressions (§15.9), which detect the out-of-memory condition before evaluating argument expressions (§15.9.6).

- -

15.11 Field Access Expressions

- -A field access expression may access a field of an object or array, a reference to which is the value of either an expression or the special keyword super. (It is also possible to refer to a field of the current instance or current class by using a simple name; see §6.5.6.)

-

-The meaning of a field access expression is determined using the same rules as for qualified names (§6.6), but limited by the fact that an expression cannot denote a package, class type, or interface type.

- -

15.11.1 Field Access Using a Primary

- -The type of the Primary must be a reference type T, or a compile-time error occurs. The meaning of the field access expression is determined as follows:

-

-Note, specifically, that only the type of the Primary expression, not the class of the actual object referred to at run time, is used in determining which field to use.

- -Thus, the example:

-

class S { int x = 0; }
-class T extends S { int x = 1; }
-class Test {
-	public static void main(String[] args) {
-		T t = new T();
-		System.out.println("t.x=" + t.x + when("t", t));
-		S s = new S();
-		System.out.println("s.x=" + s.x + when("s", s));
-		s = t;
-		System.out.println("s.x=" + s.x + when("s", s));
-	}
-	static String when(String name, Object t) {
-		return " when " + name + " holds a "
-			+ t.getClass() + " at run time.";
-	}
-}
-
-produces the output:

-

t.x=1 when t holds a class T at run time.
-s.x=0 when s holds a class S at run time.
-s.x=0 when s holds a class T at run time.
-
-The last line shows that, indeed, the field that is accessed does not depend on the run-time class of the referenced object; even if s holds a reference to an object of class T, the expression s.x refers to the x field of class S, because the type of the expression s is S. Objects of class T contain two fields named x, one for class T and one for its superclass S.

- -This lack of dynamic lookup for field accesses allows programs to be run efficiently with straightforward implementations. The power of late binding and overriding is available in, but only when instance methods are used. Consider the same example using instance methods to access the fields:

-

class S { int x = 0; int z() { return x; } }
-class T extends S { int x = 1; int z() { return x; } }
-class Test {
-	public static void main(String[] args) {
-		T t = new T();
-		System.out.println("t.z()=" + t.z() + when("t", t));
-		S s = new S();
-		System.out.println("s.z()=" + s.z() + when("s", s));
-		s = t;
-		System.out.println("s.z()=" + s.z() + when("s", s));
-	}
-	static String when(String name, Object t) {
-		return " when " + name + " holds a "
-			+ t.getClass() + " at run time.";
-	}
-}
-
-Now the output is:

-

t.z()=1 when t holds a class T at run time.
-s.z()=0 when s holds a class S at run time.
-s.z()=1 when s holds a class T at run time.
-
-The last line shows that, indeed, the method that is accessed does depend on the run-time class of referenced object; when s holds a reference to an object of class T, the expression s.z() refers to the z method of class T, despite the fact that the type of the expression s is S. Method z of class T overrides method z of class S.

- -The following example demonstrates that a null reference may be used to access a class (static) variable without causing an exception:

-

class Test {
-	static String mountain = "Chocorua";
-	static Test favorite(){
-		System.out.print("Mount ");
-		return null;
-	}
-	public static void main(String[] args) {
-		System.out.println(favorite().mountain);
-	}
-}
-
-It compiles, executes, and prints:

-

Mount Chocorua
-
- -Even though the result of favorite() is null, a NullPointerException is not thrown. That "Mount " is printed demonstrates that the Primary expression is indeed fully evaluated at run time, despite the fact that only its type, not its value, is used to determine which field to access (because the field mountain is static).

- -

15.11.2 Accessing Superclass Members using super

- -The special forms using the keyword super are valid only in an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class; these are exactly the same situations in which the keyword this may be used (§15.8.3). The forms involving super may not be used anywhere in the class Object, since Object has no superclass; if super appears in class Object, then a compile-time error results.

- -Suppose that a field access expression super.name appears within class C, and the immediate superclass of C is class S. Then super.name is treated exactly as if it had been the expression ((S)this).name; thus, it refers to the field named name of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named name that is visible in class S, even if that field is hidden by a declaration of a field named name in class C.

- -The use of super is demonstrated by the following example:

-

interface I { int x = 0; }
-class T1 implements I { int x = 1; }
-class T2 extends T1 { int x = 2; }
-class T3 extends T2 {
-	int x = 3;
-	void test() {
-		System.out.println("x=\t\t"+x);
-		System.out.println("super.x=\t\t"+super.x);
-		System.out.println("((T2)this).x=\t"+((T2)this).x);
-		System.out.println("((T1)this).x=\t"+((T1)this).x);
-		System.out.println("((I)this).x=\t"+((I)this).x);
-	}
-}
-class Test {
-	public static void main(String[] args) {
-		new T3().test();
-	}
-}
-
-which produces the output:

-

x=					3
-super.x=					2
-((T2)this).x=					2
-((T1)this).x=					1
-((I)this).x=					0
-
-Within class T3, the expression super.x is treated exactly as if it were:

-

((T2)this).x
-
-Suppose that a field access expression T.super.name appears within class C, and the immediate superclass of the class denoted by T is a class whose fully qualified name is S. Then T.super.name is treated exactly as if it had been the expression ((S)T.this).name.

- -Thus the expression T.super.name can access the field named name that is visible in the class named by S, even if that field is hidden by a declaration of a field named name in the class named by T.

- -It is a compile-time error if the class denoted by T is not a lexically enclosing class of the current class.

- -

15.12 Method Invocation Expressions

- -A method invocation expression is used to invoke a class or instance method.

-

-The definition of ArgumentList from §15.9 is repeated here for convenience:

-

- -Resolving a method name at compile time is more complicated than resolving a field name because of the possibility of method overloading. Invoking a method at run time is also more complicated than accessing a field because of the possibility of instance method overriding.

- -Determining the method that will be invoked by a method invocation expression involves several steps. The following three sections describe the compile-time processing of a method invocation; the determination of the type of the method invocation expression is described in §15.12.3.

- -

15.12.1 Compile-Time Step 1: Determine Class or Interface to Search

- -The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to check for definitions of methods of that name. There are several cases to consider, depending on the form that precedes the left parenthesis, as follows:

-

-

15.12.2 Compile-Time Step 2: Determine Method Signature

- -The second step searches the class or interface determined in the previous step for method declarations. This step uses the name of the method and the types of the argument expressions to locate method declarations that are both applicable and accessible, that is, declarations that can be correctly invoked on the given arguments. There may be more than one such method declaration, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method declaration is one used at run time to do the method dispatch.

- -

15.12.2.1 Find Methods that are Applicable and Accessible

- -A method declaration is applicable to a method invocation if and only if both of the following are true:

-

-The class or interface determined by the process described in §15.12.1 is searched for all method declarations applicable to this method invocation; method definitions inherited from superclasses and superinterfaces are included in this search.

- -Whether a method declaration is accessible (§6.6) at a method invocation depends on the access modifier (public, none, protected, or private) in the method declaration and on where the method invocation appears.

- -If the class or interface has no method declaration that is both applicable and accessible, then a compile-time error occurs.

- -In the example program:

-

public class Doubler {
-	static int two() { return two(1); }
-	private static int two(int i) { return 2*i; }
-}
-class Test extends Doubler {	
-	public static long two(long j) {return j+j; }
-	public static void main(String[] args) {
-		System.out.println(two(3));
-		System.out.println(Doubler.two(3)); // compile-time error
-	}
-}
-
-for the method invocation two(1) within class Doubler, there are two accessible methods named two, but only the second one is applicable, and so that is the one invoked at run time. For the method invocation two(3) within class Test, there are two applicable methods, but only the one in class Test is accessible, and so that is the one to be invoked at run time (the argument 3 is converted to type long). For the method invocation Doubler.two(3), the class Doubler, not class Test, is searched for methods named two; the only applicable method is not accessible, and so this method invocation causes a compile-time error.

- -Another example is:

-

class ColoredPoint {
-	int x, y;
-	byte color;
-	void setColor(byte color) { this.color = color; }
-}
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint cp = new ColoredPoint();
-		byte color = 37;
-		cp.setColor(color);
-		cp.setColor(37);											// compile-time error
-	}
-}
-
-Here, a compile-time error occurs for the second invocation of setColor, because no applicable method can be found at compile time. The type of the literal 37 is int, and int cannot be converted to byte by method invocation conversion. Assignment conversion, which is used in the initialization of the variable color, performs an implicit conversion of the constant from type int to byte, which is permitted because the value 37 is small enough to be represented in type byte; but such a conversion is not allowed for method invocation conversion.

- -If the method setColor had, however, been declared to take an int instead of a byte, then both method invocations would be correct; the first invocation would be allowed because method invocation conversion does permit a widening conversion from byte to int. However, a narrowing cast would then be required in the body of setColor:

-

	void setColor(int color) { this.color = (byte)color; }
-
-

15.12.2.2 Choose the Most Specific Method

- -If more than one method declaration is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

- -The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

- -The precise definition is as follows. Let m be a name and suppose that there are two declarations of methods named m, each having n parameters. Suppose that one declaration appears within a class or interface T and that the types of the parameters are T1, . . . , Tn; suppose moreover that the other declaration appears within a class or interface U and that the types of the parameters are U1, . . . , Un. Then the method m declared in T is more specific than the method m declared in U if and only if both of the following are true:

-

-A method is said to be maximally specific for a method invocation if it is applicable and accessible and there is no other applicable and accessible method that is more specific.

- -If there is exactly one maximally specific method, then it is in fact the most specific method; it is necessarily more specific than any other method that is applicable and accessible. It is then subjected to some further compile-time checks as described in §15.12.3.

- -It is possible that no method is the most specific, because there are two or more maximally specific methods. In this case:

-

-

15.12.2.3 Example: Overloading Ambiguity

- -Consider the example:

-

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-
-class Test {
-	static void test(ColoredPoint p, Point q) {
-		System.out.println("(ColoredPoint, Point)");
-	}
-	static void test(Point p, ColoredPoint q) {
-		System.out.println("(Point, ColoredPoint)");
-	}
-	public static void main(String[] args) {
-		ColoredPoint cp = new ColoredPoint();
-		test(cp, cp);											// compile-time error
-	}
-}
-
-This example produces an error at compile time. The problem is that there are two declarations of test that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous.

- -If a third definition of test were added:

-

	static void test(ColoredPoint p, ColoredPoint q) {
-		System.out.println("(ColoredPoint, ColoredPoint)");
-	}
-
-then it would be more specific than the other two, and the method invocation would no longer be ambiguous.

- -

15.12.2.4 Example: Return Type Not Considered

- -As another example, consider:

-

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-class Test {
-	static int test(ColoredPoint p) {
-		return p.color;
-	}
-	static String test(Point p) {
-		return "Point";
-	}
-	public static void main(String[] args) {
-		ColoredPoint cp = new ColoredPoint();
-		String s = test(cp);											// compile-time error
-	}
-}
-
-Here the most specific declaration of method test is the one taking a parameter of type ColoredPoint. Because the result type of the method is int, a compile-time error occurs because an int cannot be converted to a String by assignment conversion. This example shows that the result types of methods do not participate in resolving overloaded methods, so that the second test method, which returns a String, is not chosen, even though it has a result type that would allow the example program to compile without error.

- -

15.12.2.5 Example: Compile-Time Resolution

- -The most applicable method is chosen at compile time; its descriptor determines what method is actually executed at run time. If a new method is added to a class, then source code that was compiled with the old definition of the class might not use the new method, even if a recompilation would cause this method to be chosen.

- -So, for example, consider two compilation units, one for class Point:

-

package points;
-public class Point {
-	public int x, y;
-	public Point(int x, int y) { this.x = x; this.y = y; }
-	public String toString() { return toString(""); }
-	public String toString(String s) {
-		return "(" + x + "," + y + s + ")";
-	}
-}
-
-and one for class ColoredPoint:

-

package points;
-public class ColoredPoint extends Point {
-	public static final int
-		RED = 0, GREEN = 1, BLUE = 2;
-	public static String[] COLORS =
-		{ "red", "green", "blue" };
-	public byte color;
-	public ColoredPoint(int x, int y, int color) {
-		super(x, y); this.color = (byte)color;
-	}
-	/** Copy all relevant fields of the argument into
-		    this ColoredPoint object. */
-	public void adopt(Point p) { x = p.x; y = p.y; }
-	public String toString() {
-		String s = "," + COLORS[color];
-		return super.toString(s);
-	}
-}
-
-Now consider a third compilation unit that uses ColoredPoint:

-

import points.*;
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint cp =
-			new ColoredPoint(6, 6, ColoredPoint.RED);
-		ColoredPoint cp2 =
-			new ColoredPoint(3, 3, ColoredPoint.GREEN);
-		cp.adopt(cp2);
-		System.out.println("cp: " + cp);
-	}
-}
-
-The output is:

-

cp: (3,3,red)
-
- -The application programmer who coded class Test has expected to see the word green, because the actual argument, a ColoredPoint, has a color field, and color would seem to be a "relevant field" (of course, the documentation for the package Points ought to have been much more precise!).

- -Notice, by the way, that the most specific method (indeed, the only applicable method) for the method invocation of adopt has a signature that indicates a method of one parameter, and the parameter is of type Point. This signature becomes part of the binary representation of class Test produced by the compiler and is used by the method invocation at run time.

- -Suppose the programmer reported this software error and the maintainer of the points package decided, after due deliberation, to correct it by adding a method to class ColoredPoint:

-

-public void adopt(ColoredPoint p) {
-	adopt((Point)p); color = p.color;
-}
-
- -If the application programmer then runs the old binary file for Test with the new binary file for ColoredPoint, the output is still:

-

-cp: (3,3,red)
-
-because the old binary file for Test still has the descriptor "one parameter, whose type is Point; void" associated with the method call cp.adopt(cp2). If the source code for Test is recompiled, the compiler will then discover that there are now two applicable adopt methods, and that the signature for the more specific one is "one parameter, whose type is ColoredPoint; void"; running the program will then produce the desired output:

-

cp: (3,3,green)
-
- -With forethought about such problems, the maintainer of the points package could fix the ColoredPoint class to work with both newly compiled and old code, by adding defensive code to the old adopt method for the sake of old code that still invokes it on ColoredPoint arguments:

-

-public void adopt(Point p) {
-	if (p instanceof ColoredPoint)
-		color = ((ColoredPoint)p).color;
-	x = p.x; y = p.y;
-}
-
- -Ideally, source code should be recompiled whenever code that it depends on is changed. However, in an environment where different classes are maintained by different organizations, this is not always feasible. Defensive programming with careful attention to the problems of class evolution can make upgraded code much more robust. See §13 for a detailed discussion of binary compatibility and type evolution.

- -

15.12.3 Compile-Time Step 3: Is the Chosen Method Appropriate?

- -If there is a most specific method declaration for a method invocation, it is called the compile-time declaration for the method invocation. Three further checks must be made on the compile-time declaration:

-

-The following compile-time information is then associated with the method invocation for use at run time:

-

-If the compile-time declaration for the method invocation is not void, then the type of the method invocation expression is the result type specified in the compile-time declaration.

- -

15.12.4 Runtime Evaluation of Method Invocation

- -At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

- -

15.12.4.1 Compute Target Reference (If Necessary)

- -There are several cases to consider, depending on which of the four productions for MethodInvocation (§15.12) is involved:

-

-

15.12.4.2 Evaluate Arguments

- -The argument expressions are evaluated in order, from left to right. If the evaluation of any argument expression completes abruptly, then no part of any argument expression to its right appears to have been evaluated, and the method invocation completes abruptly for the same reason.

- -

15.12.4.3 Check Accessibility of Type and Method

- -Let C be the class containing the method invocation, and let T be the qualifying type of the method invocation (§13.1), and m be the name of the method, as determined at compile time (§15.12.3). An implementation of the Java programming language must insure, as part of linkage, that the method m still exists in the type T. If this is not true, then a NoSuchMethodError (which is a subclass of IncompatibleClassChangeError) occurs. If the invocation mode is interface, then the implementation must also check that the target reference type still implements the specified interface. If the target reference type does not still implement the interface, then an IncompatibleClassChangeError occurs.

- -The implementation must also insure, during linkage, that the type T and the method m are accessible. For the type T:

-

-For the method m:

-

-If either T or m is not accessible, then an IllegalAccessError occurs (§12.3).

- -

15.12.4.4 Locate Method to Invoke

- -The strategy for method lookup depends on the invocation mode.

- -If the invocation mode is static, no target reference is needed and overriding is not allowed. Method m of class T is the one to be invoked.

- -Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is null, a NullPointerException is thrown at this point. Otherwise, the target reference is said to refer to a target object and will be used as the value of the keyword this in the invoked method. The other four possibilities for the invocation mode are then considered.

- -If the invocation mode is nonvirtual, overriding is not allowed. Method m of class T is the one to be invoked.

- -Otherwise, the invocation mode is interface, virtual, or super, and overriding may occur. A dynamic method lookup is used. The dynamic lookup process starts from a class S, determined as follows:

-

-The dynamic method lookup uses the following procedure to search class S, and then the superclasses of class S, as necessary, for method m.

- -Let X be the compile-time type of the target reference of the method invocation.

-

    - -
  1. If class S contains a declaration for a non-abstract method named m with the same descriptor (same number of parameters, the same parameter types, and the same return type) required by the method invocation as determined at compile time (§15.12.3), then: -
      - -
    • If the invocation mode is super or interface, then this is the method to be invoked, and the procedure terminates. - -
    • If the invocation mode is virtual, and the declaration in S overrides (§8.4.6.1) X.m, then the method declared in S is the method to be invoked, and the procedure terminates. -
    - -
  2. Otherwise, if S has a superclass, this same lookup procedure is performed recursively using the direct superclass of S in place of S; the method to be invoked is the result of the recursive invocation of this lookup procedure. -
- -The above procedure will always find a non-abstract, accessible method to invoke, provided that all classes and interfaces in the program have been consistently compiled. However, if this is not the case, then various errors may occur. The specification of the behavior of a Java virtual machine under these circumstances is given by The Java Virtual Machine Specification, Second Edition.

- -We note that the dynamic lookup process, while described here explicitly, will often be implemented implicitly, for example as a side-effect of the construction and use of per-class method dispatch tables, or the construction of other per-class structures used for efficient dispatch.

- -

15.12.4.5 Create Frame, Synchronize, Transfer Control

- -A method m in some class S has been identified as the one to be invoked.

- -Now a new activation frame is created, containing the target reference (if any) and the argument values (if any), as well as enough space for the local variables and stack for the method to be invoked and any other bookkeeping information that may be required by the implementation (stack pointer, program counter, reference to previous activation frame, and the like). If there is not sufficient memory available to create such an activation frame, an OutOfMemoryError is thrown.

- -The newly created activation frame becomes the current activation frame. The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method, and to make the target reference available as this, if there is a target reference. Before each argument value is assigned to its corresponding parameter variable, it is subjected to method invocation conversion (§5.3), which includes any required value set conversion (§5.1.8).

- -If the method m is a native method but the necessary native, implementation-dependent binary code has not been loaded or otherwise cannot be dynamically linked, then an UnsatisfiedLinkError is thrown.

- -If the method m is not synchronized, control is transferred to the body of the method m to be invoked.

- -If the method m is synchronized, then an object must be locked before the transfer of control. No further progress can be made until the current thread can obtain the lock. If there is a target reference, then the target must be locked; otherwise the Class object for class S, the class of the method m, must be locked. Control is then transferred to the body of the method m to be invoked. The object is automatically unlocked when execution of the body of the method has completed, whether normally or abruptly. The locking and unlocking behavior is exactly as if the body of the method were embedded in a synchronized statement (§14.18).

- -

15.12.4.6 Example: Target Reference and Static Methods

- -When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:

-

class Test {
-	static void mountain() {
-		System.out.println("Monadnock");
-	}
-	static Test favorite(){
-		System.out.print("Mount ");
-		return null;
-	}
-	public static void main(String[] args) {
-		favorite().mountain();
-	}
-}
-
-which prints:

-

Mount Monadnock
-
-Here favorite returns null, yet no NullPointerException is thrown.

- -

15.12.4.7 Example: Evaluation Order

- -As part of an instance method invocation (§15.12), there is an expression that denotes the object to be invoked. This expression appears to be fully evaluated before any part of any argument expression to the method invocation is evaluated.

- -So, for example, in:

-

class Test {
-	public static void main(String[] args) {
-		String s = "one";
-		if (s.startsWith(s = "two"))
-			System.out.println("oops");
-	}
-}
-
-the occurrence of s before ".startsWith" is evaluated first, before the argument expression s="two". Therefore, a reference to the string "one" is remembered as the target reference before the local variable s is changed to refer to the string "two". As a result, the startsWith method is invoked for target object "one" with argument "two", so the result of the invocation is false, as the string "one" does not start with "two". It follows that the test program does not print "oops".

- -

15.12.4.8 Example: Overriding

- -In the example:

-

class Point {
-	final int EDGE = 20;
-	int x, y;
-	void move(int dx, int dy) {
-		x += dx; y += dy;
-		if (Math.abs(x) >= EDGE || Math.abs(y) >= EDGE)
-			clear();
-	}
-	void clear() {
-		System.out.println("\tPoint clear");
-		x = 0; y = 0;
-	}
-}
-class ColoredPoint extends Point {
-	int color;
-	void clear() {
-		System.out.println("\tColoredPoint clear");
-		super.clear();
-		color = 0;
-	}
-}
-
-the subclass ColoredPoint extends the clear abstraction defined by its superclass Point. It does so by overriding the clear method with its own method, which invokes the clear method of its superclass, using the form super.clear.

- -This method is then invoked whenever the target object for an invocation of clear is a ColoredPoint. Even the method move in Point invokes the clear method of class ColoredPoint when the class of this is ColoredPoint, as shown by the output of this test program:

-

class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		System.out.println("p.move(20,20):");
-		p.move(20, 20);
-		ColoredPoint cp = new ColoredPoint();
-		System.out.println("cp.move(20,20):");
-		cp.move(20, 20);
-		p = new ColoredPoint();
-		System.out.println("p.move(20,20), p colored:");
-		p.move(20, 20);
-	}
-}
-
-which is:

-

p.move(20,20):
-	Point clear
-cp.move(20,20):
-	ColoredPoint clear
-	Point clear
-p.move(20,20), p colored:
-	ColoredPoint clear
-	Point clear
-
- -Overriding is sometimes called "late-bound self-reference"; in this example it means that the reference to clear in the body of Point.move (which is really syntactic shorthand for this.clear) invokes a method chosen "late" (at run time, based on the run-time class of the object referenced by this) rather than a method chosen "early" (at compile time, based only on the type of this). This provides the programmer a powerful way of extending abstractions and is a key idea in object-oriented programming.

- -

15.12.4.9 Example: Method Invocation using super

- -An overridden instance method of a superclass may be accessed by using the keyword super to access the members of the immediate superclass, bypassing any overriding declaration in the class that contains the method invocation.

- -When accessing an instance variable, super means the same as a cast of this (§15.11.2), but this equivalence does not hold true for method invocation. This is demonstrated by the example:

-

class T1 {
-	String s() { return "1"; }
-}
-class T2 extends T1 {
-	String s() { return "2"; }
-}
-class T3 extends T2 {
-	String s() { return "3"; }
-	void test() {
-		System.out.println("s()=\t\t"+s());
-		System.out.println("super.s()=\t"+super.s());
-		System.out.print("((T2)this).s()=\t");
-			System.out.println(((T2)this).s());
-		System.out.print("((T1)this).s()=\t");
-			System.out.println(((T1)this).s());
-	}
-}
-class Test {
-	public static void main(String[] args) {
-		T3 t3 = new T3();
-		t3.test();
-	}
-}
-
-which produces the output:

-

s()=					3
-super.s()=					2
-((T2)this).s()=					3
-((T1)this).s()=					3
-
- -The casts to types T1 and T2 do not change the method that is invoked, because the instance method to be invoked is chosen according to the run-time class of the object referred to be this. A cast does not change the class of an object; it only checks that the class is compatible with the specified type.

- -

15.13 Array Access Expressions

- -An array access expression refers to a variable that is a component of an array.

-

-An array access expression contains two subexpressions, the array reference expression (before the left bracket) and the index expression (within the brackets). Note that the array reference expression may be a name or any primary expression that is not an array creation expression (§15.10).

- -The type of the array reference expression must be an array type (call it T[], an array whose components are of type T) or a compile-time error results. Then the type of the array access expression is T.

- -The index expression undergoes unary numeric promotion (§5.6.1); the promoted type must be int.

- -The result of an array reference is a variable of type T, namely the variable within the array selected by the value of the index expression. This resulting variable, which is a component of the array, is never considered final, even if the array reference was obtained from a final variable.

- -

15.13.1 Runtime Evaluation of Array Access

- -An array access expression is evaluated using the following procedure:

-

-

15.13.2 Examples: Array Access Evaluation Order

- -In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated. For example, in the (admittedly monstrous) expression a[(a=b)[3]], the expression a is fully evaluated before the expression (a=b)[3]; this means that the original value of a is fetched and remembered while the expression (a=b)[3] is evaluated. This array referenced by the original value of a is then subscripted by a value that is element 3 of another array (possibly the same array) that was referenced by b and is now also referenced by a.

- -Thus, the example:

-

class Test {
-	public static void main(String[] args) {
-		int[] a = { 11, 12, 13, 14 };
-		int[] b = { 0, 1, 2, 3 };
-		System.out.println(a[(a=b)[3]]);
-	}
-}
-
-prints:

-

14
-
-because the monstrous expression's value is equivalent to a[b[3]] or a[3] or 14.

- -If evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated. Thus, the example:

-

class Test {
-	public static void main(String[] args) {
-		int index = 1;
-		try {
-			skedaddle()[index=2]++;
-		} catch (Exception e) {
-			System.out.println(e + ", index=" + index);
-		}
-	}
-	static int[] skedaddle() throws Exception {
-		throw new Exception("Ciao");
-	}
-}
-
-prints:

-

java.lang.Exception: Ciao, index=1
-
-because the embedded assignment of 2 to index never occurs.

- -If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at run time, but only after all parts of the array access expression have been evaluated and only if these evaluations completed normally. Thus, the example:

-

class Test {
-	public static void main(String[] args) {
-		int index = 1;
-		try {
-			nada()[index=2]++;
-		} catch (Exception e) {
-			System.out.println(e + ", index=" + index);
-		}
-	}
-	static int[] nada() { return null; }
-}
-
-prints:

-

java.lang.NullPointerException, index=2
-
-because the embedded assignment of 2 to index occurs before the check for a null pointer. As a related example, the program:

-

class Test {
-	public static void main(String[] args) {
-		int[] a = null;
-		try {
-			int i = a[vamoose()];
-			System.out.println(i);
-		} catch (Exception e) {
-			System.out.println(e);
-		}
-	}
-	static int vamoose() throws Exception {
-		throw new Exception("Twenty-three skidoo!");
-	}
-}
-
-always prints:

-

java.lang.Exception: Twenty-three skidoo!
-
- -A NullPointerException never occurs, because the index expression must be completely evaluated before any part of the indexing operation occurs, and that includes the check as to whether the value of the left-hand operand is null.

- -

15.14 Postfix Expressions

- -Postfix expressions include uses of the postfix ++ and -- operators. Also, as discussed in §15.8, names are not considered to be primary expressions, but are handled separately in the grammar to avoid certain ambiguities. They become interchangeable only here, at the level of precedence of postfix expressions.

-

-

15.14.1 Postfix Increment Operator ++

- -A postfix expression followed by a ++ operator is a postfix increment expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

- -Note that the binary numeric promotion mentioned above may include value set conversion (§5.1.8). If necessary, value set conversion is applied to the sum prior to its being stored in the variable.

- -A variable that is declared final cannot be incremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix increment operator.

- -

15.14.2 Postfix Decrement Operator --

- -A postfix expression followed by a -- operator is a postfix decrement expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix decrement expression is the type of the variable. The result of the postfix decrement expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the postfix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable before the new value is stored.

- -Note that the binary numeric promotion mentioned above may include value set conversion (§5.1.8). If necessary, value set conversion is applied to the difference prior to its being stored in the variable.

- -A variable that is declared final cannot be decremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix decrement operator.

- -

15.15 Unary Operators

- -The unary operators include +, -, ++, --, ~, !, and cast operators. Expressions with unary operators group right-to-left, so that -~x means the same as -(~x).

-

-The following productions from §15.16 are repeated here for convenience:

-

-

15.15.1 Prefix Increment Operator ++

- -A unary expression preceded by a ++ operator is a prefix increment expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix increment expression is the type of the variable. The result of the prefix increment expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.

- -Note that the binary numeric promotion mentioned above may include value set conversion (§5.1.8). If necessary, value set conversion is applied to the sum prior to its being stored in the variable.

- -A variable that is declared final cannot be incremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix increment operator.

- -

15.15.2 Prefix Decrement Operator --

- -A unary expression preceded by a -- operator is a prefix decrement expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix decrement expression is the type of the variable. The result of the prefix decrement expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the prefix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.

- -Note that the binary numeric promotion mentioned above may include value set conversion (§5.1.8). If necessary, format conversion is applied to the difference prior to its being stored in the variable.

- -A variable that is declared final cannot be decremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix decrement operator.

- -

15.15.3 Unary Plus Operator +

- -The type of the operand expression of the unary + operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary plus expression is the promoted type of the operand. The result of the unary plus expression is not a variable, but a value, even if the result of the operand expression is a variable.

- -At run time, the value of the unary plus expression is the promoted value of the operand.

- -

15.15.4 Unary Minus Operator -

- -The type of the operand expression of the unary - operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary minus expression is the promoted type of the operand.

- -Note that unary numeric promotion performs value set conversion (§5.1.8). Whatever value set the promoted operand value is drawn from, the unary negation operation is carried out and the result is drawn from that same value set. That result is then subject to further value set conversion.

- -At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.

- -For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.

- -For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0. Unary minus merely inverts the sign of a floating-point number. Special cases of interest:

-

-

15.15.5 Bitwise Complement Operator ~

- -The type of the operand expression of the unary ~ operator must be a primitive integral type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary bitwise complement expression is the promoted type of the operand.

- -At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand; note that, in all cases, ~x equals (-x)-1.

- -

15.15.6 Logical Complement Operator !

- -The type of the operand expression of the unary ! operator must be boolean, or a compile-time error occurs. The type of the unary logical complement expression is boolean.

- -At run time, the value of the unary logical complement expression is true if the operand value is false and false if the operand value is true.

- -

15.16 Cast Expressions

- -A cast expression converts, at run time, a value of one numeric type to a similar value of another numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.

-

-See §15.15 for a discussion of the distinction between UnaryExpression and UnaryExpressionNotPlusMinus.

- -The type of a cast expression is the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the cast operator.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.

- -A cast operator has no effect on the choice of value set (§4.2.3) for a value of type float or type double. Consequently, a cast to type float within an expression that is not FP-strict (§15.4) does not necessarily cause its value to be converted to an element of the float value set, and a cast to type double within an expression that is not FP-strict does not necessarily cause its value to be converted to an element of the double value set.

- -At run time, the operand value is converted by casting conversion (§5.5) to the type specified by the cast operator.

- -Not all casts are permitted by the language. Some casts result in an error at compile time. For example, a primitive value may not be cast to a reference type. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time.

- -A ClassCastException is thrown if a cast is found at run time to be impermissible.

- -

15.17 Multiplicative Operators

- -The operators *, /, and % are called the multiplicative operators. They have the same precedence and are syntactically left-associative (they group left-to-right).

-

-The type of each of the operands of a multiplicative operator must be a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). The type of a multiplicative expression is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

- -Note that binary numeric promotion performs value set conversion (§5.1.8).

- -

15.17.1 Multiplication Operator *

- -The binary * operator performs multiplication, producing the product of its operands. Multiplication is a commutative operation if the operand expressions have no side effects. While integer multiplication is associative when the operands are all of the same type, floating-point multiplication is not associative.

- -If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

- -The result of a floating-point multiplication is governed by the rules of IEEE 754 arithmetic:

-

-Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a multiplication operator * never throws a run-time exception.

- -

15.17.2 Division Operator /

- -The binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.

- -Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying ; moreover, q is positive when and n and d have the same sign, but q is negative when and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

- -The result of a floating-point division is determined by the specification of IEEE arithmetic:

-

-Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator / never throws a run-time exception

- -

15.17.3 Remainder Operator %

- -The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.

- -In C and C++, the remainder operator accepts only integral operands, but in the Java programming language, it also accepts floating-point operands.

- -The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown.Examples:

-

-5%3 produces 2				(note that 5/3 produces 1)
-5%(-3) produces 2			(note that 5/(-3) produces -1)
-(-5)%3 produces -2			(note that (-5)/3 produces -1)
-(-5)%(-3) produces -2			(note that (-5)/(-3) produces 1)
-
-The result of a floating-point remainder operation as computed by the % operator is not the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is not analogous to that of the usual integer remainder operator. Instead, the Java programming language defines % on floating-point operations to behave in a manner analogous to that of the integer remainder operator; this may be compared with the C library function fmod. The IEEE 754 remainder operation may be computed by the library routine Math.IEEEremainder.

- -The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

-

-Evaluation of a floating-point remainder operator % never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur.

- -Examples:

-

5.0%3.0 produces 2.0
-5.0%(-3.0) produces 2.0
-(-5.0)%3.0 produces -2.0
-(-5.0)%(-3.0) produces -2.0
-
-

15.18 Additive Operators

- -The operators + and - are called the additive operators. They have the same precedence and are syntactically left-associative (they group left-to-right).

-

-If the type of either operand of a + operator is String, then the operation is string concatenation.

- -Otherwise, the type of each of the operands of the + operator must be a primitive numeric type, or a compile-time error occurs.

- -In every case, the type of each of the operands of the binary - operator must be a primitive numeric type, or a compile-time error occurs.

- -

15.18.1 String Concatenation Operator +

- -If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a newly created String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

- -

15.18.1.1 String Conversion

- -Any type may be converted to type String by string conversion.

- -A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:

-

-This reference value is then converted to type String by string conversion.

- -Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

- -The toString method is defined by the primordial class Object; many classes override it, notably Boolean, Character, Integer, Long, Float, Double, and String.

- -

15.18.1.2 Optimization of String Concatenation

- -An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

- -For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

- -

15.18.1.3 Examples of String Concatenation

- -The example expression:

-

"The square root of 2 is " + Math.sqrt(2)
-
-produces the result:

-

"The square root of 2 is 1.4142135623730952"
-
- -The + operator is syntactically left-associative, no matter whether it is later determined by type analysis to represent string concatenation or addition. In some cases care is required to get the desired result. For example, the expression:

-

-a + b + c
-
-is always regarded as meaning:

-

(a + b) + c
-
-Therefore the result of the expression:

-

1 + 2 + " fiddlers"
-
-is:

-

"3 fiddlers"
-
-but the result of:

-

"fiddlers " + 1 + 2
-
-is:

-

"fiddlers 12"
-
- -In this jocular little example:

-

-class Bottles {
-	static void printSong(Object stuff, int n) {
-		String plural = (n == 1) ? "" : "s";
-		loop: while (true) {
-			System.out.println(n + " bottle" + plural
-				+ " of " + stuff + " on the wall,");
-			System.out.println(n + " bottle" + plural
-				+ " of " + stuff + ";");
-			System.out.println("You take one down "
-				+ "and pass it around:");
-			--n;
-			plural = (n == 1) ? "" : "s";
-			if (n == 0)
-				break loop;
-			System.out.println(n + " bottle" + plural
-				+ " of " + stuff + " on the wall!");
-			System.out.println();
-		}
-		System.out.println("No bottles of " +
-								stuff + " on the wall!");
-	}
-}
-
-the method printSong will print a version of a children's song. Popular values for stuff include "pop" and "beer"; the most popular value for n is 100. Here is the output that results from Bottles.printSong("slime", 3):

-

3 bottles of slime on the wall,
-3 bottles of slime;
-You take one down and pass it around:
-2 bottles of slime on the wall!
-
-2 bottles of slime on the wall,
-2 bottles of slime;
-You take one down and pass it around:
-1 bottle of slime on the wall!
-
-1 bottle of slime on the wall,
-1 bottle of slime;
-You take one down and pass it around:
-No bottles of slime on the wall!
-
- -In the code, note the careful conditional generation of the singular "bottle" when appropriate rather than the plural "bottles"; note also how the string concatenation operator was used to break the long constant string:

-

-"You take one down and pass it around:"
-
- -into two pieces to avoid an inconveniently long line in the source code.

- -

15.18.2 Additive Operators (+ and -) for Numeric Types

- -The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands. The binary - operator performs subtraction, producing the difference of two numeric operands.

- -Binary numeric promotion is performed on the operands (§5.6.2). The type of an additive expression on numeric operands is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

- -Note that binary numeric promotion performs value set conversion (§5.1.8).

- -Addition is a commutative operation if the operand expressions have no side effects. Integer addition is associative when the operands are all of the same type, but floating-point addition is not associative.

- -If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

- -The result of a floating-point addition is determined using the following rules of IEEE arithmetic:

-

-The binary - operator performs subtraction when applied to two operands of numeric type producing the difference of its operands; the left-hand operand is the minuend and the right-hand operand is the subtrahend. For both integer and floating-point subtraction, it is always the case that a-b produces the same result as a+(-b).

- -Note that, for integer values, subtraction from zero is the same as negation. However, for floating-point operands, subtraction from zero is not the same as negation, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0.

- -Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a run-time exception.

- -

15.19 Shift Operators

- -The shift operators include left shift <<, signed right shift >>, and unsigned right shift >>>; they are syntactically left-associative (they group left-to-right). The left-hand operand of a shift operator is the value to be shifted; the right-hand operand specifies the shift distance.

-

-The type of each of the operands of a shift operator must be a primitive integral type, or a compile-time error occurs. Binary numeric promotion (§5.6.2) is not performed on the operands; rather, unary numeric promotion (§5.6.1) is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.

- -If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

- -If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

- -At run time, shift operations are performed on the two's complement integer representation of the value of the left operand.

- -The value of n<<s is n left-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s.

- -The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is . For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.

- -The value of n>>>s is n right-shifted s bit positions with zero-extension. If n is positive, then the result is the same as that of n>>s; if n is negative, the result is equal to that of the expression (n>>s)+(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)+(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a long value.)

- -

15.20 Relational Operators

- -The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.

-

-The type of a relational expression is always boolean.

- -

15.20.1 Numerical Comparison Operators <, <=, >, and >=

- -The type of each of the operands of a numerical comparison operator must be a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

- -Note that binary numeric promotion performs value set conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.

- -The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:

-

-Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

-

-

15.20.2 Type Comparison Operator instanceof

- -The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs.

- -At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

- -If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

- -Consider the example program:

-

class Point { int x, y; }
-class Element { int atomicNumber; }
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		Element e = new Element();
-		if (e instanceof Point) {											// compile-time error
-			System.out.println("I get your point!");
-			p = (Point)e;										// compile-time error
-		}
-	}
-}
-
-This example results in two compile-time errors. The cast (Point)e is incorrect because no instance of Element or any of its possible subclasses (none are shown here) could possibly be an instance of any subclass of Point. The instanceof expression is incorrect for exactly the same reason. If, on the other hand, the class Point were a subclass of Element (an admittedly strange notion in this example):

-

class Point extends Element { int x, y; }
-
-then the cast would be possible, though it would require a run-time check, and the instanceof expression would then be sensible and valid. The cast (Point)e would never raise an exception because it would not be executed if the value of e could not correctly be cast to type Point.

- -

15.21 Equality Operators

- -The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, a==b==c parses as (a==b)==c. The result type of a==b is always boolean, and c must therefore be of type boolean or a compile-time error occurs. Thus, a==b==c does not test to see whether a, b, and c are all equal.

-

-The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.

- -The equality operators may be used to compare two operands of numeric type, or two operands of type boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.

- -In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.

- -

15.21.1 Numerical Equality Operators == and !=

- -If the operands of an equality operator are both of primitive numeric type, binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

- -Note that binary numeric promotion performs value set conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.

- -Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

-

-Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

-

-

15.21.2 Boolean Equality Operators == and !=

- -If the operands of an equality operator are both of type boolean, then the operation is boolean equality. The boolean equality operators are associative.

- -The result of == is true if the operands are both true or both false; otherwise, the result is false.

- -The result of != is false if the operands are both true or both false; otherwise, the result is true. Thus != behaves the same as ^ (§15.22.2) when applied to boolean operands.

- -

15.21.3 Reference Equality Operators == and !=

- -If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

- -A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal.

- -At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

- -The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.

- -While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of two strings s and t can be tested for equality by the method invocation s.equals(t). See also §3.10.5.

- -

15.22 Bitwise and Logical Operators

- -The bitwise operators and logical operators include the AND operator &, exclusive OR operator ^, and inclusive OR operator |. These operators have different precedence, with & having the highest precedence and | the lowest precedence. Each of these operators is syntactically left-associative (each groups left-to-right). Each operator is commutative if the operand expressions have no side effects. Each operator is associative.

-

-The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type boolean. All other cases result in a compile-time error.

- -

15.22.1 Integer Bitwise Operators &, ^, and |

- -When both operands of an operator &, ^, or | are of primitive integral type, binary numeric promotion is first performed on the operands (§5.6.2). The type of the bitwise operator expression is the promoted type of the operands.

- -For &, the result value is the bitwise AND of the operand values.

- -For ^, the result value is the bitwise exclusive OR of the operand values.

- -For |, the result value is the bitwise inclusive OR of the operand values.

- -For example, the result of the expression 0xff00 & 0xf0f0 is 0xf000. The result of 0xff00 ^ 0xf0f0 is 0x0ff0.The result of 0xff00 | 0xf0f0 is 0xfff0.

- -

15.22.2 Boolean Logical Operators &, ^, and |

- -When both operands of a &, ^, or | operator are of type boolean, then the type of the bitwise operator expression is boolean.

- -For &, the result value is true if both operand values are true; otherwise, the result is false.

- -For ^, the result value is true if the operand values are different; otherwise, the result is false.

- -For |, the result value is false if both operand values are false; otherwise, the result is true.

- -

15.23 Conditional-And Operator &&

- -The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)&&(b))&&(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)&&((b)&&(c)).

-

-Each operand of && must be of type boolean, or a compile-time error occurs. The type of a conditional-and expression is always boolean.

- -At run time, the left-hand operand expression is evaluated first; if its value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

- -

15.24 Conditional-Or Operator ||

- -The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)||(b))||(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)||((b)||(c)).

-

-Each operand of || must be of type boolean, or a compile-time error occurs. The type of a conditional-or expression is always boolean.

- -At run time, the left-hand operand expression is evaluated first; if its value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression.

- -Thus, || computes the same result as | on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

- -

15.25 Conditional Operator ? :

- -The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

- -The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

-

-The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.

- -The first expression must be of type boolean, or a compile-time error occurs.

- -The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type boolean, or second and third operands that are each of either reference type or the null type. All other cases result in a compile-time error.

- -Note that it is not permitted for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear (§14.8).

- -The type of a conditional expression is determined as follows:

-

-At run time, the first operand expression of the conditional expression is evaluated first; its boolean value is then used to choose either the second or the third operand expression:

-

-The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated above. The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.

- -

15.26 Assignment Operators

- -There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

-

-The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. This operand may be a named variable, such as a local variable or a field of the current object or class, or it may be a computed variable, as can result from a field access (§15.11) or an array access (§15.13). The type of the assignment expression is the type of the variable.

- -At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

- -A variable that is declared final cannot be assigned to (unless it is a blank final variable (§4.5.4)), because when an access of a final variable is used as an expression, the result is a value, not a variable, and so it cannot be used as the first operand of an assignment operator.

- -

15.26.1 Simple Assignment Operator =

- -A compile-time error occurs if the type of the right-hand operand cannot be converted to the type of the variable by assignment conversion (§5.2).

- -At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then three steps are required:

-

-If the left-hand operand expression is an array access expression (§15.13), then many steps are required:

-

-Otherwise, the reference value of the right-hand operand is stored into the selected array component.

- -The rules for assignment to an array component are illustrated by the following example program:

-

class ArrayReferenceThrow extends RuntimeException { }
-class IndexThrow extends RuntimeException { }
-class RightHandSideThrow extends RuntimeException { }
-class IllustrateSimpleArrayAssignment {
-	static Object[] objects = { new Object(), new Object() };
-	static Thread[] threads = { new Thread(), new Thread() };
-	static Object[] arrayThrow() {
-		throw new ArrayReferenceThrow();
-	}
-	static int indexThrow() { throw new IndexThrow(); }
-	static Thread rightThrow() {
-		throw new RightHandSideThrow();
-	}
-	static String name(Object q) {
-		String sq = q.getClass().getName();
-		int k = sq.lastIndexOf('.');
-		return (k < 0) ? sq : sq.substring(k+1);
-	}
-	static void testFour(Object[] x, int j, Object y) {
-		String sx = x == null ? "null" : name(x[0]) + "s";
-		String sy = name(y);
-		System.out.println();
-		try {
-			System.out.print(sx + "[throw]=throw => ");
-			x[indexThrow()] = rightThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sx + "[throw]=" + sy + " => ");
-			x[indexThrow()] = y;
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sx + "[" + j + "]=throw => ");
-			x[j] = rightThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sx + "[" + j + "]=" + sy + " => ");
-			x[j] = y;
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-	}
-	public static void main(String[] args) {
-		try {
-			System.out.print("throw[throw]=throw => ");
-			arrayThrow()[indexThrow()] = rightThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[throw]=Thread => ");
-			arrayThrow()[indexThrow()] = new Thread();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[1]=throw => ");
-			arrayThrow()[1] = rightThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[1]=Thread => ");
-			arrayThrow()[1] = new Thread();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		testFour(null, 1, new StringBuffer());
-		testFour(null, 1, new StringBuffer());
-		testFour(null, 9, new Thread());
-		testFour(null, 9, new Thread());
-		testFour(objects, 1, new StringBuffer());
-		testFour(objects, 1, new Thread());
-		testFour(objects, 9, new StringBuffer());
-		testFour(objects, 9, new Thread());
-		testFour(threads, 1, new StringBuffer());
-		testFour(threads, 1, new Thread());
-		testFour(threads, 9, new StringBuffer());
-		testFour(threads, 9, new Thread());
-	}
-}
-
-This program prints:

-

throw[throw]=throw => ArrayReferenceThrow
-throw[throw]=Thread => ArrayReferenceThrow
-throw[1]=throw => ArrayReferenceThrow
-throw[1]=Thread => ArrayReferenceThrow
-null[throw]=throw => IndexThrow
-null[throw]=StringBuffer => IndexThrow
-null[1]=throw => RightHandSideThrow
-null[1]=StringBuffer => NullPointerException
-null[throw]=throw => IndexThrow
-null[throw]=StringBuffer => IndexThrow
-null[1]=throw => RightHandSideThrow
-null[1]=StringBuffer => NullPointerException
-null[throw]=throw => IndexThrow
-null[throw]=Thread => IndexThrow
-null[9]=throw => RightHandSideThrow
-null[9]=Thread => NullPointerException
-null[throw]=throw => IndexThrow
-null[throw]=Thread => IndexThrow
-null[9]=throw => RightHandSideThrow
-null[9]=Thread => NullPointerException
-Objects[throw]=throw => IndexThrow
-Objects[throw]=StringBuffer => IndexThrow
-Objects[1]=throw => RightHandSideThrow
-Objects[1]=StringBuffer => Okay!
-Objects[throw]=throw => IndexThrow
-Objects[throw]=Thread => IndexThrow
-Objects[1]=throw => RightHandSideThrow
-Objects[1]=Thread => Okay!
-Objects[throw]=throw => IndexThrow
-Objects[throw]=StringBuffer => IndexThrow
-Objects[9]=throw => RightHandSideThrow
-Objects[9]=StringBuffer => ArrayIndexOutOfBoundsException
-Objects[throw]=throw => IndexThrow
-Objects[throw]=Thread => IndexThrow
-Objects[9]=throw => RightHandSideThrow
-Objects[9]=Thread => ArrayIndexOutOfBoundsException
-Threads[throw]=throw => IndexThrow
-Threads[throw]=StringBuffer => IndexThrow
-Threads[1]=throw => RightHandSideThrow
-Threads[1]=StringBuffer => ArrayStoreException
-Threads[throw]=throw => IndexThrow
-Threads[throw]=Thread => IndexThrow
-Threads[1]=throw => RightHandSideThrow
-Threads[1]=Thread => Okay!
-Threads[throw]=throw => IndexThrow
-Threads[throw]=StringBuffer => IndexThrow
-Threads[9]=throw => RightHandSideThrow
-Threads[9]=StringBuffer => ArrayIndexOutOfBoundsException
-Threads[throw]=throw => IndexThrow
-Threads[throw]=Thread => IndexThrow
-Threads[9]=throw => RightHandSideThrow
-Threads[9]=Thread => ArrayIndexOutOfBoundsException
-
-The most interesting case of the lot is the one thirteenth from the end:

-

Threads[1]=StringBuffer => ArrayStoreException
-
-which indicates that the attempt to store a reference to a StringBuffer into an array whose components are of type Thread throws an ArrayStoreException. The code is type-correct at compile time: the assignment has a left-hand side of type Object[] and a right-hand side of type Object. At run time, the first actual argument to method testFour is a reference to an instance of "array of Thread" and the third actual argument is a reference to an instance of class StringBuffer.

- -

15.26.2 Compound Assignment Operators

- -All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.

- -A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. Note that the implied cast to type T may be either an identity conversion (§5.1.1) or a narrowing primitive conversion (§5.1.3). For example, the following code is correct:

-


-short x = 3;
-x += 4.6;
-
-and results in x having the value 7 because it is equivalent to:

-


-short x = 3;
-x = (short)(x + 4.6);
-
-At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:

-

-If the left-hand operand expression is an array access expression (§15.13), then many steps are required:

-

-Otherwise, the String result of the binary operation is stored into the array component.

- -The rules for compound assignment to an array component are illustrated by the following example program:

-

class ArrayReferenceThrow extends RuntimeException { }
-class IndexThrow extends RuntimeException { }
-class RightHandSideThrow extends RuntimeException { }
-class IllustrateCompoundArrayAssignment {
-	static String[] strings = { "Simon", "Garfunkel" };
-	static double[] doubles = { Math.E, Math.PI };
-	static String[] stringsThrow() {
-		throw new ArrayReferenceThrow();
-	}
-	static double[] doublesThrow() {
-		throw new ArrayReferenceThrow();
-	}
-	static int indexThrow() { throw new IndexThrow(); }
-	static String stringThrow() {
-		throw new RightHandSideThrow();
-	}
-	static double doubleThrow() {
-		throw new RightHandSideThrow();
-	}
-	static String name(Object q) {
-		String sq = q.getClass().getName();
-		int k = sq.lastIndexOf('.');
-		return (k < 0) ? sq : sq.substring(k+1);
-	}
-	static void testEight(String[] x, double[] z, int j) {
-		String sx = (x == null) ? "null" : "Strings";
-		String sz = (z == null) ? "null" : "doubles";
-		System.out.println();
-		try {
-			System.out.print(sx + "[throw]+=throw => ");
-			x[indexThrow()] += stringThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sz + "[throw]+=throw => ");
-			z[indexThrow()] += doubleThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sx + "[throw]+=\"heh\" => ");
-			x[indexThrow()] += "heh";
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sz + "[throw]+=12345 => ");
-			z[indexThrow()] += 12345;
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sx + "[" + j + "]+=throw => ");
-			x[j] += stringThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sz + "[" + j + "]+=throw => ");
-			z[j] += doubleThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sx + "[" + j + "]+=\"heh\" => ");
-			x[j] += "heh";
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print(sz + "[" + j + "]+=12345 => ");
-			z[j] += 12345;
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-	}
-	public static void main(String[] args) {
-		try {
-			System.out.print("throw[throw]+=throw => ");
-			stringsThrow()[indexThrow()] += stringThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[throw]+=throw => ");
-			doublesThrow()[indexThrow()] += doubleThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[throw]+=\"heh\" => ");
-			stringsThrow()[indexThrow()] += "heh";
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[throw]+=12345 => ");
-			doublesThrow()[indexThrow()] += 12345;
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[1]+=throw => ");
-			stringsThrow()[1] += stringThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[1]+=throw => ");
-			doublesThrow()[1] += doubleThrow();
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[1]+=\"heh\" => ");
-			stringsThrow()[1] += "heh";
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		try {
-			System.out.print("throw[1]+=12345 => ");
-			doublesThrow()[1] += 12345;
-			System.out.println("Okay!");
-		} catch (Throwable e) { System.out.println(name(e)); }
-		testEight(null, null, 1);
-		testEight(null, null, 9);
-		testEight(strings, doubles, 1);
-		testEight(strings, doubles, 9);
-	}
-}
-
-This program prints:

-

throw[throw]+=throw => ArrayReferenceThrow
-throw[throw]+=throw => ArrayReferenceThrow
-throw[throw]+="heh" => ArrayReferenceThrow
-throw[throw]+=12345 => ArrayReferenceThrow
-throw[1]+=throw => ArrayReferenceThrow
-throw[1]+=throw => ArrayReferenceThrow
-throw[1]+="heh" => ArrayReferenceThrow
-throw[1]+=12345 => ArrayReferenceThrow
-null[throw]+=throw => IndexThrow
-null[throw]+=throw => IndexThrow
-null[throw]+="heh" => IndexThrow
-null[throw]+=12345 => IndexThrow
-null[1]+=throw => NullPointerException
-null[1]+=throw => NullPointerException
-null[1]+="heh" => NullPointerException
-null[1]+=12345 => NullPointerException
-null[throw]+=throw => IndexThrow
-null[throw]+=throw => IndexThrow
-null[throw]+="heh" => IndexThrow
-null[throw]+=12345 => IndexThrow
-null[9]+=throw => NullPointerException
-null[9]+=throw => NullPointerException
-null[9]+="heh" => NullPointerException
-null[9]+=12345 => NullPointerException
-Strings[throw]+=throw => IndexThrow
-doubles[throw]+=throw => IndexThrow
-Strings[throw]+="heh" => IndexThrow
-doubles[throw]+=12345 => IndexThrow
-Strings[1]+=throw => RightHandSideThrow
-doubles[1]+=throw => RightHandSideThrow
-Strings[1]+="heh" => Okay!
-doubles[1]+=12345 => Okay!
-Strings[throw]+=throw => IndexThrow
-doubles[throw]+=throw => IndexThrow
-Strings[throw]+="heh" => IndexThrow
-doubles[throw]+=12345 => IndexThrow
-Strings[9]+=throw => ArrayIndexOutOfBoundsException
-doubles[9]+=throw => ArrayIndexOutOfBoundsException
-Strings[9]+="heh" => ArrayIndexOutOfBoundsException
-doubles[9]+=12345 => ArrayIndexOutOfBoundsException
-
-The most interesting cases of the lot are tenth and eleventh from the end:

-

Strings[1]+=throw => RightHandSideThrow
-doubles[1]+=throw => RightHandSideThrow
-
-They are the cases where a right-hand side that throws an exception actually gets to throw the exception; moreover, they are the only such cases in the lot. This demonstrates that the evaluation of the right-hand operand indeed occurs after the checks for a null array reference value and an out-of-bounds index value.

- -The following program illustrates the fact that the value of the left-hand side of a compound assignment is saved before the right-hand side is evaluated:

-

class Test {
-	public static void main(String[] args) {
-		int k = 1;
-		int[] a = { 1 };
-		k += (k = 4) * (k + 2);
-		a[0] += (a[0] = 4) * (a[0] + 2);
-		System.out.println("k==" + k + " and a[0]==" + a[0]);
-	}
-}
-
-This program prints:

-

k==25 and a[0]==25
-
-The value 1 of k is saved by the compound assignment operator += before its right-hand operand (k = 4) * (k + 2) is evaluated. Evaluation of this right-hand operand then assigns 4 to k, calculates the value 6 for k + 2, and then multiplies 4 by 6 to get 24. This is added to the saved value 1 to get 25, which is then stored into k by the += operator. An identical analysis applies to the case that uses a[0]. In short, the statements

-

k += (k = 4) * (k + 2);
-a[0] += (a[0] = 4) * (a[0] + 2);
-
-behave in exactly the same manner as the statements:

-

k = k + (k = 4) * (k + 2);
-a[0] = a[0] + (a[0] = 4) * (a[0] + 2);
-
-

15.27 Expression

- -An Expression is any assignment expression:

-

- -Unlike C and C++, the Java programming language has no comma operator.

- -

15.28 Constant Expression

- -A compile-time constant expression is an expression denoting a value of primitive type or a String that is composed using only the following:

-

-Compile-time constant expressions are used in case labels in switch statements (§14.10) and have a special significance for assignment conversion (§5.2).

- -A compile-time constant expression is always treated as FP-strict (§15.4), even if it occurs in a context where a non-constant expression would not be considered to be FP-strict.

- -Examples of constant expressions:

-

true
-(short)(1*2*3*4*5*6)
-Integer.MAX_VALUE / 2
-2.0 * Math.PI
-"The integer " + Long.MAX_VALUE + " is mighty big."
-
- -
- - - -
Contents | Prev | Next | IndexJava Language Specification
-Second Edition
-Copyright © 2000 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form - - diff --git a/topics/java/jls2/impl.html b/topics/java/jls2/impl.html new file mode 100644 index 00000000..b0aed839 --- /dev/null +++ b/topics/java/jls2/impl.html @@ -0,0 +1,239 @@ + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/syntax.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/syntax.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + diff --git a/topics/java/jls2/read.html b/topics/java/jls2/read.html new file mode 100644 index 00000000..6e747d6d --- /dev/null +++ b/topics/java/jls2/read.html @@ -0,0 +1,1912 @@ + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/typesValues.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/typesValues.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/names.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/names.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/packages.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/packages.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/classes.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/classes.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/interfaces.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/interfaces.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/arrays.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/arrays.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/statements.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/statements.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/second_edition/html/expressions.read.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/second_edition/html/expressions.read.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + diff --git a/topics/java/jls3/Makefile b/topics/java/jls3/Makefile index 1546424c..0d85ed01 100644 --- a/topics/java/jls3/Makefile +++ b/topics/java/jls3/Makefile @@ -1,25 +1,25 @@ all: - make app - make doc + make impl + make read make test debug: - python ../../extraction/html2bgf/html2bgf.py app.html app3.bgf -v - python ../../extraction/html2bgf/getpre.py collect.kw doc.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html doc3.bgf -v + python ../../extraction/html2bgf/html2bgf.py impl.html impl3.bgf -v + python ../../extraction/html2bgf/getpre.py collect.kw read.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html read3.bgf -v -app: - @echo "Extracting app3" > /dev/stderr - python ../../extraction/html2bgf/html2bgf.py app.html app3.bgf +impl: + @echo "Extracting impl3" > /dev/stderr + python ../../extraction/html2bgf/html2bgf.py impl.html impl3.bgf -doc: - @echo "Extracting doc3" > /dev/stderr - python ../../extraction/html2bgf/getpre.py collect.kw doc.html parse.html - python ../../extraction/html2bgf/html2bgf.py parse.html doc3.bgf +read: + @echo "Extracting read3" > /dev/stderr + python ../../extraction/html2bgf/getpre.py collect.kw read.html parse.html + python ../../extraction/html2bgf/html2bgf.py parse.html read3.bgf test: - ../../../shared/tools/checkxml bgf app3.bgf - ../../../shared/tools/checkxml bgf doc3.bgf + ../../../shared/tools/checkxml bgf impl3.bgf + ../../../shared/tools/checkxml bgf read3.bgf clean: rm -f *.bgf parse.html diff --git a/topics/java/jls3/app.html b/topics/java/jls3/app.html deleted file mode 100644 index 2494a89c..00000000 --- a/topics/java/jls3/app.html +++ /dev/null @@ -1,541 +0,0 @@ - - - Syntax - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- - -

-CHAPTER - 18

- -

Syntax

-

- -This chapter presents a grammar for the Java programming language.

- -The grammar presented piecemeal in the preceding chapters is much better for exposition, but it is not well suited as a basis for a parser. The grammar presented in this chapter is the basis for the reference implementation. Note that it is not an LL(1) grammar, though in many cases it minimizes the necessary look ahead.

- -The grammar below uses the following BNF-style conventions:

-

-x | y means one of either x or y.

- - -

18.1 The Grammar of the Java Programming Language

-

-Identifier:
-        IDENTIFIER
-
-QualifiedIdentifier:
-        Identifier { . Identifier }
-
-Literal:
-        IntegerLiteral
-        FloatingPointLiteral
-        CharacterLiteral
-        StringLiteral
-        BooleanLiteral
-        NullLiteral
-
-Expression:
-        Expression1 [AssignmentOperator Expression1]]
-
-AssignmentOperator: 
-        =
-        +=
-        -=
-        *=
-        /=
-        &=
-        |=
-        ^=
-        %=
-        <<=
-        >>=
-        >>>=
-
-Type:
-        Identifier [TypeArguments]{   .   Identifier [TypeArguments]} {[]}
-        BasicType
-
-TypeArguments:
-        < TypeArgument {, TypeArgument} >
-
-TypeArgument:
-        Type
-        ? [( extends |super ) Type]
-
-StatementExpression:
-        Expression
-
-ConstantExpression:
-        Expression
-
-Expression1:
-        Expression2 [Expression1Rest]
-
-Expression1Rest:
-        ?   Expression   :   Expression1
-
-Expression2 :
-        Expression3 [Expression2Rest]
-
-Expression2Rest:
-        {InfixOp Expression3}
-        Expression3 instanceof Type
-
-InfixOp:
-        ||
-        &&
-        |
-        ^
-        &
-        ==
-        !=
-        <
-        >
-        <=
-        >=
-        <<
-        >>
-        >>>
-        +
-        -
-        *
-        /
-        %
-
-Expression3:
-        PrefixOp Expression3
-        (   Expression | Type   )   Expression3
-        Primary {Selector} {PostfixOp}
-
-Primary:
-        ParExpression
-        NonWildcardTypeArguments (ExplicitGenericInvocationSuffix | this
-Arguments)
-  this [Arguments]
-  super SuperSuffix
-        Literal
-  new Creator
-        Identifier { . Identifier }[ IdentifierSuffix]
-        BasicType {[]} .class
-   void.class
-
-IdentifierSuffix:
-        [ ( ] {[]} .   class | Expression ])
-        Arguments
-        .   ( class | ExplicitGenericInvocation | this | super Arguments | new
-[NonWildcardTypeArguments] InnerCreator )
-
-ExplicitGenericInvocation:
-        NonWildcardTypeArguments ExplicitGenericInvocationSuffix
-
-NonWildcardTypeArguments:
-        < TypeList >
-
-
-ExplicitGenericInvocationSuffix:
-     super SuperSuffix
-        Identifier Arguments
-
-
-PrefixOp:
-        ++
-        --
-        !
-        ~
-        +
-        -
-
-PostfixOp:
-        ++
-        --
-
-Selector: Selector:
-        . Identifier [Arguments]
-        . ExplicitGenericInvocation
-        . this
-   . super SuperSuffix
-        . new [NonWildcardTypeArguments] InnerCreator
-        [ Expression ]
-
-SuperSuffix:
-        Arguments
-        . Identifier [Arguments]
-
-BasicType:
-  byte
-  short
-  char
-  int
-  long
-  float
-  double
-  boolean
-
-Arguments:
-        ( [Expression { , Expression }] )
-
-Creator:
-        [NonWildcardTypeArguments] CreatedName ( ArrayCreatorRest  |
-ClassCreatorRest )
-
-CreatedName:
-        Identifier [NonWildcardTypeArguments] {. Identifier
-[NonWildcardTypeArguments]}
-
-InnerCreator:
-        Identifier ClassCreatorRest
-
-ArrayCreatorRest:
-        [ ( ] {[]} ArrayInitializer | Expression ] {[ Expression ]} {[]} )
-
-ClassCreatorRest:
-         Arguments [ClassBody]
-
-ArrayInitializer:
-        { [VariableInitializer {, VariableInitializer} [,]] }
-
-VariableInitializer:
-        ArrayInitializer
-        Expression
-
-ParExpression:
-        ( Expression )
-
-Block:
-        { BlockStatements }
-
-BlockStatements:
-        { BlockStatement }
-
-BlockStatement :
-        LocalVariableDeclarationStatement
-        ClassOrInterfaceDeclaration
-        [Identifier :] Statement
-
-LocalVariableDeclarationStatement:
-        [final] Type VariableDeclarators   ;
-
-Statement:
-        Block
-        assert Expression [ : Expression] ;
-     if ParExpression Statement [else Statement]
-     for ( ForControl ) Statement
-     while ParExpression Statement
-     do Statement while ParExpression   ;
-     try Block ( Catches | [Catches] finally Block )
-     switch ParExpression { SwitchBlockStatementGroups }
-     synchronized ParExpression Block
-     return [Expression] ;
-     throw Expression   ;
-     break [Identifier]
-     continue [Identifier]
-        ;
-        StatementExpression ;
-        Identifier   :   Statement
-
-Catches:
-        CatchClause {CatchClause}
-
-CatchClause:
-     catch ( FormalParameter ) Block
-
-SwitchBlockStatementGroups:
-        { SwitchBlockStatementGroup }
-
-SwitchBlockStatementGroup:
-        SwitchLabel BlockStatements
-
-SwitchLabel:
-     case ConstantExpression   :
-        case EnumConstantName :
-        default   :
-
-MoreStatementExpressions:
-        { , StatementExpression }
-
-ForControl:
-        ForVarControl
-        ForInit;   [Expression]   ; [ForUpdate]
-
-ForVarControl
-        [final] [Annotations] Type Identifier ForVarControlRest
-
-Annotations:
-        Annotation [Annotations]
-
-Annotation:
-        @ TypeName [( [Identifier =] ElementValue)]
-
-ElementValue:
-        ConditionalExpression
-        Annotation
-        ElementValueArrayInitializer
-
-ConditionalExpression:
-        Expression2 Expression1Rest
-
-    ElementValueArrayInitializer:
-        { [ElementValues] [,] }
-
-    ElementValues:
-        ElementValue [ElementValues]
-
-ForVarControlRest:
-        VariableDeclaratorsRest;   [Expression]   ;   [ForUpdate]
-        : Expression
-
-ForInit:
-        StatementExpression Expressions
-
-Modifier:
-  Annotation
-  public
-  protected
-  private
-  static
-  abstract
-  final
-  native
-  synchronized
-  transient
-  volatile
-        strictfp
-
-VariableDeclarators:
-        VariableDeclarator { ,   VariableDeclarator }
-
-VariableDeclaratorsRest:
-        VariableDeclaratorRest { ,   VariableDeclarator }
-
-ConstantDeclaratorsRest:
-        ConstantDeclaratorRest { ,   ConstantDeclarator }
-
-VariableDeclarator:
-        Identifier VariableDeclaratorRest
-
-ConstantDeclarator:
-        Identifier ConstantDeclaratorRest
-
-VariableDeclaratorRest:
-        {[]} [  =   VariableInitializer]
-
-ConstantDeclaratorRest:
-        {[]} =   VariableInitializer
-
-VariableDeclaratorId:
-        Identifier {[]}
-
-CompilationUnit:
-        [[Annotations] package QualifiedIdentifier   ;  ] {ImportDeclaration}
-{TypeDeclaration}
-
-ImportDeclaration:
-     import [ static] Identifier {   .   Identifier } [   .     *   ] ;
-
-TypeDeclaration:
-        ClassOrInterfaceDeclaration
-        ;
-
-ClassOrInterfaceDeclaration:
-        {Modifier} (ClassDeclaration | InterfaceDeclaration)
-
-ClassDeclaration:
-        NormalClassDeclaration
-        EnumDeclaration
-
-NormalClassDeclaration:
-     class Identifier [TypeParameters] [extends Type] [implements TypeList]
-ClassBody
-
-TypeParameters:
-        < TypeParameter {, TypeParameter} >
-
-TypeParameter:
-        Identifier [extends Bound]
-
-Bound:
-         Type {& Type}
-
-
-EnumDeclaration:
-        enum Identifier [implements TypeList] EnumBody
-
-EnumBody:
-        { [EnumConstants] [,] [EnumBodyDeclarations] }
-
-EnumConstants:
-        EnumConstant
-        EnumConstants , EnumConstant
-
-EnumConstant:
-        Annotations Identifier [Arguments] [ClassBody]
-
-EnumBodyDeclarations:
-        ; {ClassBodyDeclaration}
-
-InterfaceDeclaration:
-        NormalInterfaceDeclaration
-        AnnotationTypeDeclaration
-
-NormalInterfaceDeclaration:
-     interface Identifier [ TypeParameters] [extends TypeList] InterfaceBody
-
-TypeList:
-        Type {  ,   Type}
-
-AnnotationTypeDeclaration:
-        @ interface Identifier AnnotationTypeBody
-
-    AnnotationTypeBody:
-        { [AnnotationTypeElementDeclarations] }
-
-    AnnotationTypeElementDeclarations:
-        AnnotationTypeElementDeclaration
-        AnnotationTypeElementDeclarations AnnotationTypeElementDeclaration
-
-AnnotationTypeElementDeclaration:
-        {Modifier} AnnotationTypeElementRest
-
-AnnotationTypeElementRest:
-         Type Identifier AnnotationMethodOrConstantRest;
-        ClassDeclaration
-        InterfaceDeclaration
-        EnumDeclaration
-        AnnotationTypeDeclaration
-
-        AnnotationMethodOrConstantRest:
-        AnnotationMethodRest
-        AnnotationConstantRest
-
-AnnotationMethodRest:
-        ( ) [DefaultValue]
-
-AnnotationConstantRest:
-        VariableDeclarators
-
-
-    DefaultValue:
-        default ElementValue
-
-ClassBody:
-        { {ClassBodyDeclaration} }
-
-InterfaceBody:
-        { {InterfaceBodyDeclaration} }
-
-ClassBodyDeclaration:
-        ;
-        [static] Block
-        {Modifier} MemberDecl
-
-MemberDecl:
-        GenericMethodOrConstructorDecl
-        MethodOrFieldDecl
-        void Identifier VoidMethodDeclaratorRest
-        Identifier ConstructorDeclaratorRest
-        InterfaceDeclaration
-        ClassDeclaration
-
-GenericMethodOrConstructorDecl:
-        TypeParameters GenericMethodOrConstructorRest
-
-GenericMethodOrConstructorRest:
-        (Type | void) Identifier MethodDeclaratorRest
-        Identifier ConstructorDeclaratorRest
-
-MethodOrFieldDecl:
-        Type Identifier MethodOrFieldRest
-
-MethodOrFieldRest:
-        VariableDeclaratorRest
-        MethodDeclaratorRest
-
-InterfaceBodyDeclaration:
-        ;
-        {Modifier} InterfaceMemberDecl
-
-InterfaceMemberDecl:
-        InterfaceMethodOrFieldDecl
-        InterfaceGenericMethodDecl
-        void Identifier VoidInterfaceMethodDeclaratorRest
-        InterfaceDeclaration
-        ClassDeclaration
-
-InterfaceMethodOrFieldDecl:
-        Type Identifier InterfaceMethodOrFieldRest
-
-InterfaceMethodOrFieldRest:
-        ConstantDeclaratorsRest ;
-        InterfaceMethodDeclaratorRest
-
-MethodDeclaratorRest:
-        FormalParameters {[]} [throws QualifiedIdentifierList] ( MethodBody |   ;
-)
-
-VoidMethodDeclaratorRest:
-        FormalParameters [throws QualifiedIdentifierList] ( MethodBody |   ;  )
-
-InterfaceMethodDeclaratorRest:
-        FormalParameters {[]} [throws QualifiedIdentifierList]   ;
-
-InterfaceGenericMethodDecl:
-        TypeParameters (Type | void) Identifier InterfaceMethodDeclaratorRest
-
-VoidInterfaceMethodDeclaratorRest:
-        FormalParameters [throws QualifiedIdentifierList]   ;
-
-ConstructorDeclaratorRest:
-        FormalParameters [throws QualifiedIdentifierList] MethodBody
-
-QualifiedIdentifierList:
-        QualifiedIdentifier {  ,   QualifiedIdentifier}
-
-FormalParameters:
-        ( [FormalParameterDecls] )
-
-FormalParameterDecls:
-        [final] [Annotations] Type FormalParameterDeclsRest]
-
-FormalParameterDeclsRest:
-        VariableDeclaratorId [ , FormalParameterDecls]
-        ... VariableDeclaratorId
-
-MethodBody:
-        Block
-
-EnumConstantName:
-        Identifier
-
-

- - -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- \ No newline at end of file diff --git a/topics/java/jls3/doc.html b/topics/java/jls3/doc.html deleted file mode 100644 index 09389002..00000000 --- a/topics/java/jls3/doc.html +++ /dev/null @@ -1,13958 +0,0 @@ - - - Types, Values, and Variables - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 4

- -

Types, Values, and Variables

-

- -The Java programming language is a strongly typed language, which means that every variable and every expression has a type that is known at compile time. Types limit the values that a variable (§4.12) can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong typing helps detect errors at compile time.

- -The types of the Java programming language are divided into two categories: primitive types and reference types. The primitive types (§4.2) are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types (§4.3) are class types, interface types, and array types. There is also a special null type. An object (§4.3.1) is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object (§4.3.2). String literals are represented by String objects (§4.3.3).

- -

- -Types exist at compile-time. Some types correspond to classes and interfaces, which exist at run-time. The correspondence between types and classes or interfaces is incomplete for two reasons:

-

    - -
  1. At run-time, classes and interfaces are loaded by the Java virtual machine using class loaders. Each class loader defines its own set of classes and interfaces. As a result, it is possible for two loaders to load an identical class or interface definition but produce distinct classes or interfaces at run-time. - -
  2. Type arguments and type variables (§4.4) are not reified at run-time. As a result, different parameterized types (§4.5) are implemented by the same class or interface at run time. Indeed, all invocations of a given generic type declaration (§8.1.2, §9.1.2 )share a single run-time implementation. -
- -A consequence of (1) is that code that compiled correctly may fail at link time if the class loaders that load it are inconsistent. See the paper Dynamic Class Loading in the Java Virtual Machine, by Sheng Liang and Gilad Bracha, in Proceedings of OOPSLA '98, published as ACM SIGPLAN Notices, Volume 33, Number 10, October 1998, pages 36-44, and The Java Virtual Machine Specification, Second Edition for more details.

- -A consequence of (2) is the possibility of heap pollution (§4.12.2.1). Under certain conditions, it is possible that a variable of a parameterized type refers to an object that is not of that parameterized type. The variable will always refer to an object that is an instance of a class that implements the parameterized type. See (§4.12.2) for further discussion.

- - -

4.1 The Kinds of Types and Values

- -There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).

-

-
-Type:
-        PrimitiveType
-        ReferenceType
-        
-
-There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

- - -

4.2 Primitive Types and Values

- -A primitive type is predefined by the Java programming language and named by its reserved keyword (§3.9):

-

-
-PrimitiveType:
-        NumericType
-        boolean
-
-NumericType:
-        IntegralType
-        FloatingPointType
-
-IntegralType: one of
-        byte short int long char
-
-FloatingPointType: one of
-        float double
-
-Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable (including increment (§15.14.2, §15.15.1) and decrement (§15.14.3, §15.15.2) operators).

- -The numeric types are the integral types and the floating-point types.

- -The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).

- -The floating-point types are float, whose values include the 32-bit IEEE 754 floating-point numbers, and double, whose values include the 64-bit IEEE 754 floating-point numbers.

- -The boolean type has exactly two values: true and false.

- - -

4.2.1 Integral Types and Values

- -The values of the integral types are integers in the following ranges:

-

- -

4.2.2 Integer Operations

- -The Java programming language provides a number of operators that act on integral values:

-

-Other useful constructors, methods, and constants are predefined in the classes Byte, Short, Integer, Long, and Character.

- -If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

- -The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a NullPointerException if unboxing conversion (§5.1.8) of a null reference is required. Other than that, the only integer operators that can throw an exception (§11) are the integer divide operator / (§15.17.2) and the integer remainder operator % (§15.17.3), which throw an ArithmeticException if the right-hand operand is zero, and the increment and decrement operators ++(§15.15.1, §15.15.2) and --(§15.14.3, §15.14.2), which can throw an OutOfMemoryError if boxing conversion (§5.1.7) is required and there is not sufficient memory available to perform the conversion.

- -

The example:

-
class Test {
-        public static void main(String[] args) {
-                int i = 1000000;
-                System.out.println(i * i);
-                long l = i;
-                System.out.println(l * l);
-                System.out.println(20296 / (l - i));
-        }
-}
-
-produces the output:

-

-727379968
-1000000000000
-
-and then encounters an ArithmeticException in the division by l - i, because l - i is zero. The first multiplication is performed in 32-bit precision, whereas the second multiplication is a long multiplication. The value -727379968 is the decimal value of the low 32 bits of the mathematical result, 1000000000000, which is a value too large for type int.

- -Any value of any integral type may be cast to or from any numeric type. There are no casts between integral types and the type boolean.

- - -

4.2.3 Floating-Point Types, Formats, and Values

- -The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).

- -The IEEE 754 standard includes not only positive and negative numbers that consist of a sign and magnitude, but also positive and negative zeros, positive and negative infinities, and special Not-a-Number values (hereafter abbreviated NaN). A NaN value is used to represent the result of certain invalid operations such as dividing zero by zero. NaN constants of both float and double type are predefined as Float.NaN and Double.NaN.

- -Every implementation of the Java programming language is required to support two standard sets of floating-point values, called the float value set and the double value set. In addition, an implementation of the Java programming language may support either or both of two extended-exponent floating-point value sets, called the float-extended-exponent value set and the double-extended-exponent value set. These extended-exponent value sets may, under certain circumstances, be used instead of the standard value sets to represent the values of expressions of type float or double (§5.1.13, §15.4).

- -The finite nonzero values of any floating-point value set can all be expressed in the form s · m · 2(e-N+1), where s is +1 or -1, m is a positive integer less than 2N, and e is an integer between Emin = -(2K-1-2) and Emax = 2K-1-1, inclusive, and where N and K are parameters that depend on the value set. Some values can be represented in this form in more than one way; for example, supposing that a value v in a value set might be represented in this form using certain values for s, m, and e, then if it happened that m were even and e were less than 2K-1, one could halve m and increase e by 1 to produce a second representation for the same value v. A representation in this form is called normalized if m 2(N-1); otherwise the representation is said to be denormalized. If a value in a value set cannot be represented in such a way that m 2(N-1), then the value is said to be a denormalized value, because it has no normalized representation.

- -The constraints on the parameters N and K (and on the derived parameters Emin and Emax) for the two required and two optional floating-point value sets are summarized in Table 4.1. -

- -
- -Parameter - - - float - - - float-extended-exponent - - - double - - - double-extended-exponent - -
- N

-

- 24

-

- 24

-

- 53

-

- 53

- -

- K

-

- 8

-

- 11

-

- 11

-

- 15

- -

- Emax

-

- +127

-

- +1023

-

- +1023

-

- +16383

- -

- Emin

-

- -126

-

- -1022

-

- -1022

-

- -16382

- - -

- - -
-
-

- -Where one or both extended-exponent value sets are supported by an implementation, then for each supported extended-exponent value set there is a specific implementation-dependent constant K, whose value is constrained by Table 4.1; this value K in turn dictates the values for Emin and Emax.

- -Each of the four value sets includes not only the finite nonzero values that are ascribed to it above, but also NaN values and the four values positive zero, negative zero, positive infinity, and negative infinity.

- -Note that the constraints in Table 4.1 are designed so that every element of the float value set is necessarily also an element of the float-extended-exponent value set, the double value set, and the double-extended-exponent value set. Likewise, each element of the double value set is necessarily also an element of the double-extended-exponent value set. Each extended-exponent value set has a larger range of exponent values than the corresponding standard value set, but does not have more precision.

- -The elements of the float value set are exactly the values that can be represented using the single floating-point format defined in the IEEE 754 standard. The elements of the double value set are exactly the values that can be represented using the double floating-point format defined in the IEEE 754 standard. Note, however, that the elements of the float-extended-exponent and double-extended-exponent value sets defined here do not correspond to the values that can be represented using IEEE 754 single extended and double extended formats, respectively.

- -The float, float-extended-exponent, double, and double-extended-exponent value sets are not types. It is always correct for an implementation of the Java programming language to use an element of the float value set to represent a value of type float; however, it may be permissible in certain regions of code for an implementation to use an element of the float-extended-exponent value set instead. Similarly, it is always correct for an implementation to use an element of the double value set to represent a value of type double; however, it may be permissible in certain regions of code for an implementation to use an element of the double-extended-exponent value set instead.

- -Except for NaN, floating-point values are ordered; arranged from smallest to largest, they are negative infinity, negative finite nonzero values, positive and negative zero, positive finite nonzero values, and positive infinity.

- -IEEE 754 allows multiple distinct NaN values for each of its single and double floating-point formats. While each hardware architecture returns a particular bit pattern for NaN when a new NaN is generated, a programmer can also create NaNs with different bit patterns to encode, for example, retrospective diagnostic information.

- -For the most part, the Java platform treats NaN values of a given type as though collapsed into a single canonical value (and hence this specification normally refers to an arbitrary NaN as though to a canonical value). However, version 1.3 the Java platform introduced methods enabling the programmer to distinguish between NaN values: the Float.floatToRawIntBits and Double.doubleToRawLongBits methods. The interested reader is referred to the specifications for the Float and Double classes for more information.

- -Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity.

- -NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.

- -Any value of a floating-point type may be cast to or from any numeric type. There are no casts between floating-point types and the type boolean.

- - -

4.2.4 Floating-Point Operations

- -The Java programming language provides a number of operators that act on floating-point values:

-

-Other useful constructors, methods, and constants are predefined in the classes Float, Double, and Math.

- -If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

- -If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. (If the other operand is not a double, it is first widened to type double by numeric promotion (§5.6).) Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. If the other operand is not a float, it is first widened to type float by numeric promotion.

- -Operators on floating-point numbers behave as specified by IEEE 754 (with the exception of the remainder operator (§15.17.3)). In particular, the Java programming language requires support of IEEE 754 denormalized floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations do not "flush to zero" if the calculated result is a denormalized number.

- -The Java programming language requires that floating-point arithmetic behave as if every floating-point operator rounded its floating-point result to the result precision. Inexact results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, the one with its least significant bit zero is chosen. This is the IEEE 754 standard's default rounding mode known as round to nearest.

- -The language uses round toward zero when converting a floating value to an integer (§5.1.3), which acts, in this case, as though the number were truncated, discarding the mantissa bits. Rounding toward zero chooses at its result the format's value closest to and no greater in magnitude than the infinitely precise result.

- -Floating-point operators can throw a NullPointerException if unboxing conversion (§5.1.8) of a null reference is required. Other than that, the only floating-point operators that can throw an exception (§11) are the increment and decrement operators ++(§15.15.1, §15.15.2) and --(§15.14.3, §15.14.2), which can throw an OutOfMemoryError if boxing conversion (§5.1.7) is required and there is not sufficient memory available to perform the conversion.

- -An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN.

- -

The example program:

-
class Test {
-        public static void main(String[] args) {
-                // An example of overflow:
-                double d = 1e308;
-                System.out.print("overflow produces infinity: ");
-                System.out.println(d + "*10==" + d*10);
-                // An example of gradual underflow:
-                d = 1e-305 * Math.PI;
-                System.out.print("gradual underflow: " + d + "\n      ");
-                for (int i = 0; i < 4; i++)
-                        System.out.print(" " + (d /= 100000));
-                System.out.println();
-                // An example of NaN:
-                System.out.print("0.0/0.0 is Not-a-Number: ");
-                d = 0.0/0.0;
-                System.out.println(d);
-                // An example of inexact results and rounding:
-                System.out.print("inexact results with float:");
-                for (int i = 0; i < 100; i++) {
-                        float z = 1.0f / i;
-                        if (z * i != 1.0f)
-                                System.out.print(" " + i);
-                }
-                System.out.println();
-                // Another example of inexact results and rounding:
-                System.out.print("inexact results with double:");
-                for (int i = 0; i < 100; i++) {
-                        double z = 1.0 / i;
-                        if (z * i != 1.0)
-                                System.out.print(" " + i);
-                }
-                System.out.println();
-                // An example of cast to integer rounding:
-                System.out.print("cast to int rounds toward 0: ");
-                d = 12345.6;
-                System.out.println((int)d + " " + (int)(-d));
-        }
-}
-
-produces the output:

-

overflow produces infinity: 1.0e+308*10==Infinity
-gradual underflow: 3.141592653589793E-305
-        3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0
-0.0/0.0 is Not-a-Number: NaN
-inexact results with float: 0 41 47 55 61 82 83 94 97
-inexact results with double: 0 49 98
-cast to int rounds toward 0: 12345 -12345
-
- -

This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision.

- -

The results when i is 0 involve division by zero, so that z becomes positive infinity, and z * 0 is NaN, which is not equal to 1.0.

- - -

4.2.5 The boolean Type and boolean Values

- -The boolean type represents a logical quantity with two possible values, indicated by the literals true and false (§3.10.3). The boolean operators are:

-

-Boolean expressions determine the control flow in several kinds of statements:

-

-A boolean expression also determines which subexpression is evaluated in the conditional ? : operator (§15.25).

- -Only boolean or Boolean expressions can be used in control flow statements and as the first operand of the conditional operator ? :. An integer x can be converted to a boolean, following the C language convention that any nonzero value is true, by the expression x!=0. An object reference obj can be converted to a boolean, following the C language convention that any reference other than null is true, by the expression obj!=null.

- -A cast of a boolean value to type boolean or Boolean is allowed (§5.1.1); no other casts on type boolean are allowed. A boolean can be converted to a string by string conversion (§5.4).

- - -

4.3 Reference Types and Values

- -There are three kinds of reference types: class types (§8), interface types (§9), and array types (§10). Reference types may be parameterized (§4.5) with type arguments (§4.4).

-

-
-ReferenceType:
-        ClassOrInterfaceType
-        TypeVariable
-        ArrayType
-
-ClassOrInterfaceType:
-        ClassType
-        InterfaceType
-
-
-ClassType:
-        TypeDeclSpecifier TypeArgumentsopt
-
-InterfaceType:
-        TypeDeclSpecifier TypeArgumentsopt
-
-TypeDeclSpecifier:
-        TypeName
-        ClassOrInterfaceType . Identifier
-        
-
-

-

-
-TypeName:
-        Identifier
-        TypeName . Identifier
-
-TypeVariable:
-        Identifier
-
-ArrayType:
-        Type [ ]
-
-A class or interface type consists of a type declaration specifier, optionally followed by type arguments (in which case it is a parameterized type). Type arguments are described in (§4.5.1).

- -A type declaration specifier may be either a type name (§6.5.5), or a class or interface type followed by "." and an identifier. In the latter case, the specifier has the form T.id, where id must be the simple name of an accessible (§6.6) member type ( §8.5, §9.5) of T, or a compile-time error occurs. The specifier denotes that member type.

- -

The sample code:

-
class Point { int[] metrics; }
-interface Move { void move(int deltax, int deltay); }
-
-declares a class type Point, an interface type Move, and uses an array type int[] (an array of int) to declare the field metrics of the class Point.

- - -

4.3.1 Objects

- -An object is a class instance or an array.

- -The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

- -A class instance is explicitly created by a class instance creation expression (§15.9). An array is explicitly created by an array creation expression (§15.10).

- -A new class instance is implicitly created when the string concatenation operator + (§15.18.1) is used in a non-constant (§15.28) expression, resulting in a new object of type String (§4.3.3). A new array object is implicitly created when an array initializer expression (§10.6) is evaluated; this can occur when a class or interface is initialized (§12.4), when a new instance of a class is created (§15.9), or when a local variable declaration statement is executed (§14.4). New objects of the types Boolean, Byte, Short, Character, Integer, Long, Float and Double may be implicitly created by boxing conversion (§5.1.7).

- -

Many of these cases are illustrated in the following example:

-
class Point {
-        int x, y;
-        Point() { System.out.println("default"); }
-        Point(int x, int y) { this.x = x; this.y = y; }
-        // A Point instance is explicitly created at class initialization time:
-        static Point origin = new Point(0,0);
-        // A String can be implicitly created by a + operator:
-        public String toString() {
-                return "(" + x + "," + y + ")";
-        }
-}
-class Test {
-        public static void main(String[] args) {
-                // A Point is explicitly created using newInstance:
-                Point p = null;
-                try {
-                        p = (Point)Class.forName("Point").newInstance();
-                } catch (Exception e) {
-                        System.out.println(e);
-                }
-                // An array is implicitly created by an array constructor:
-                Point a[] = { new Point(0,0), new Point(1,1) };
-                // Strings are implicitly created by + operators:
-                System.out.println("p: " + p);
-                System.out.println("a: { " + a[0] + ", "
-                                                                                   + a[1] + " }");
-                // An array is explicitly created by an array creation expression:
-                String sa[] = new String[2];
-                sa[0] = "he"; sa[1] = "llo";
-                System.out.println(sa[0] + sa[1]);
-        }
-}
-
-which produces the output:

-

default
-p: (0,0)
-a: { (0,0), (1,1) }
-hello
-
-The operators on references to objects are:

-

-There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.

- -

The example program:

-
class Value { int val; }
-class Test {
-        public static void main(String[] args) {
-                int i1 = 3;
-                int i2 = i1;
-                i2 = 4;
-                System.out.print("i1==" + i1);
-                System.out.println(" but i2==" + i2);
-                Value v1 = new Value();
-                v1.val = 5;
-                Value v2 = v1;
-                v2.val = 6;
-                System.out.print("v1.val==" + v1.val);
-                System.out.println(" and v2.val==" + v2.val);
-        }
-}
-
-produces the output:

-

i1==3 but i2==4
-v1.val==6 and v2.val==6
-
-because v1.val and v2.val reference the same instance variable (§4.12.3) in the one Value object created by the only new expression, while i1 and i2 are different variables.

- -

See §10 and §15.10 for examples of the creation and use of arrays.

- -Each object has an associated lock (§17.1), which is used by synchronized methods (§8.4.3) and the synchronized statement (§14.19) to provide control over concurrent access to state by multiple threads (§17).

- - -

4.3.2 The Class Object

- -The class Object is a superclass (§8.1) of all other classes. A variable of type Object can hold a reference to the null reference or to any object, whether it is an instance of a class or an array (§10). All class and array types inherit the methods of class Object, which are summarized here:

-

-package java.lang;
-
-public class Object {
-    public final Class<?> getClass() { . . . }
-    public String toString() { . . . }
-    public boolean equals(Object obj) { . . . }
-    public int hashCode() { . . . }
-    protected Object clone()
-            throws CloneNotSupportedException { . . . }
-    public final void wait()
-                throws IllegalMonitorStateException,
-                        InterruptedException { . . . }
-    public final void wait(long millis)
-            throws IllegalMonitorStateException,
-                    InterruptedException { . . . }
-    public final void wait(long millis, int nanos) { . . . }
-            throws IllegalMonitorStateException,
-                    InterruptedException { . . . }
-    public final void notify() { . . . }
-            throws IllegalMonitorStateException
-    public final void notifyAll() { . . . }
-            throws IllegalMonitorStateException
-    protected void finalize()
-            throws Throwable { . . . }
-}
-
-The members of Object are as follows:

-

- -

4.3.3 The Class String

- -Instances of class String represent sequences of Unicode characters. A String object has a constant (unchanging) value. String literals (§3.10.5) are references to instances of class String.

- -The string concatenation operator + (§15.18.1) implicitly creates a new String object when the result is not a compile-time constant (§15.28).

- - -

4.3.4 When Reference Types Are the Same

- -Two reference types are the same compile-time type if they have the same binary name (§13.1) and their type parameters, if any, are the same, applying this definition recursively. When two reference types are the same, they are sometimes said to be the same class or the same interface.

- -At run time, several reference types with the same binary name may be loaded simultaneously by different class loaders. These types may or may not represent the same type declaration. Even if two such types do represent the same type declaration, they are considered distinct.

- -Two reference types are the same run-time type if:

-

- -

4.4 Type Variables

- -A type variable (§4.4) is an unqualified identifier. Type variables are introduced by generic class declarations (§8.1.2) generic interface declarations (§9.1.2) generic method declarations (§8.4.4) and by generic constructor declarations (§8.8.4).

-

-TypeParameter:
-        TypeVariable TypeBoundopt
-
-TypeBound:
-        extends ClassOrInterfaceType AdditionalBoundListopt
-
-AdditionalBoundList:
-        AdditionalBound AdditionalBoundList
-        AdditionalBound
-
-AdditionalBound:
-        & InterfaceType
-
-Type variables have an optional bound, T & I1 ... In. The bound consists of either a type variable, or a class or interface type T possibly followed by further interface types I1 , ..., In. If no bound is given for a type variable, Object is assumed. It is a compile-time error if any of the types I1 ... In is a class type or type variable. The erasures (§4.6) of all constituent types of a bound must be pairwise different, or a compile-time error occurs. The order of types in a bound is only significant in that the erasure of a type variable is determined by the first type in its bound, and that a class type or type variable may only appear in the first position.

- -

A type variable may not at the same time be a subtype of two interface types which are different parameterizations of the same generic interface.

- -See section §6.3 for the rules defining the scope of type variables.

- -The members of a type variable X with bound T & I1 ... In are the members of the intersection type (§4.9) T & I1 ... In appearing at the point where the type variable is declared.

- -

- -


-

-Discussion -

- The following example illustrates what members a type variable has.

-

package TypeVarMembers;
-
-        class C { 
-                void mCDefault() {}     
-                public void mCPublic() {}       
-                private void mCPrivate() {} 
-                protected void mCProtected() {} 
-        } 
-        class CT extends C implements I {}
-        interface I {   
-                void mI(); } 
-                <T extends C & I> void test(T t) {    
-                        t.mI(); // OK
-                        t.mCDefault(); // OK
-                        t.mCPublic(); // OK 
-                        t.mCPrivate(); // compile-time error
-                        t.mCProtected(); // OK 
-                } 
-        }
-
-The type variable T has the same members as the intersection type C & I, which in turn has the same members as the empty class CT, defined in the same scope with equivalent supertypes. The members of an interface are always public, and therefore always inherited (unless overridden). Hence mI is a member of CT and of T. Among the members of C, all but mCPrivate are inherited by CT, and are therefore members of both CT and T.

- -If C had been declared in a different package than T, then the call to mCDefault would give rise to a compile-time error, as that member would not be accessible at the point where T is declared.

-


- -

- -

- - -

4.5 Parameterized Types

- -A parameterized type consists of a class or interface name C and an actual type argument list <T1 , ... , Tn>. It is a compile time error if C is not the name of a generic class or interface, or if the number of type arguments in the actual type argument list differs from the number of declared type parameters of C. In the following, whenever we speak of a class or interface type, we include the generic version as well, unless explicitly excluded. Throughout this section, let A1 , ... , An be the formal type parameters of C, and let be Bi be the declared bound of Ai. The notation [Ai := Ti] denotes substitution of the type variable Ai with the type Ti, for 1in, and is used throughout this specification.

- -Let P = G<T1, ..., Tn> be a parameterized type. It must be the case that, after P is subjected to capture conversion (§5.1.10) resulting in the type G<X1, ..., Xn>, for each actual type argument Xi, 1in , Xi <: Bi[A1 := X1, ..., An := Xn] (§4.10), or a compile time error occurs.

- -

-


-

-Discussion -

- - Example: Parameterized types.

-

Vector<String> 
-Seq<Seq<A>> 
-Seq<String>.Zipper<Integer>
-Collection<Integer> 
-Pair<String,String>
-
-// Vector<int> -- illegal, primitive types cannot be arguments
-// Pair<String> -- illegal, not enough arguments
-// Pair<String,String,String> -- illegal, too many arguments
-
-
-
-

- -Two parameterized types are provably distinct if either of the following conditions hold:

-

- -

4.5.1 Type Arguments and Wildcards

- -Type arguments may be either reference types or wildcards.

-

-
-TypeArguments:
-        < ActualTypeArgumentList >
-
-ActualTypeArgumentList: 
-        ActualTypeArgument
-        ActualTypeArgumentList , ActualTypeArgument
-
-

- -

-

-
-ActualTypeArgument:
-        ReferenceType
-        Wildcard
-
-
-
-Wildcard:
-? WildcardBoundsOpt
-
-
-
-WildcardBounds:
-        extends ReferenceType
-        super ReferenceType
-        
-
-

-


-

-Discussion -

- - Examples

-

void printCollection(Collection<?> c) {  // a wildcard collection
-  for (Object o : c) {
-    System.out.println(o);
-  }
-}
-
- -

- Note that using Collection<Object> as the type of the incoming parameter, c, would not be nearly as useful; the method could only be used with an actual parameter that had type Collection<Object>, which would be quite rare. In contrast, the use of an unbounded wildcard allows any kind of collection to be used as a parameter.

- -

-


- -Wildcards are useful in situations where only partial knowledge about the -type parameter is required. -

-


-

- Discussion -

- - Example - Wildcard parameterized types as component types of array types.

- -

public Method getMethod(Class<?>[] parameterTypes) { ... }
-
-
-Wildcards may be given explicit bounds, just like regular type variable declarations. An upper bound is signified by the syntax:

-

? extends B
-
-, where B is the bound.

- -

-


-

- Discussion -

- - Example: Bounded wildcards.

- -

boolean addAll(Collection<? extends E> c)
-
- -

-Here, the method is declared within the interface Collection<E>, and is designed to add all the elements of its incoming argument to the collection upon which it is invoked. A natural tendency would be to use Collection<E> as the type of c, but this is unnecessarily restrictive. An alternative would be to declare the method itself to be generic:

-

-<T> boolean addAll(Collection<T> c)
-
- -

- This version is sufficiently flexible, but note that the type parameter is used only once in the signature. This reflects the fact that the type parameter is not being used to express any kind of interdependency between the type(s) of the argument(s), the return type and/or throws type. In the absence of such interdependency, generic methods are considered bad style, and wildcards are preferred. - -


-

-Unlike ordinary type variables declared in a method signature, no type inference is required when using a wildcard. Consequently, it is permissible to declare lower bounds on a wildcard, using the syntax: -

? super B
-
-, where B is a lower bound.

- -


-

- Discussion -

-

-Example: Lower bounds on wildcards. -

Reference(T referent, ReferenceQueue<? super T> queue);
-
- - Here, the referent can be inserted into any queue whose element type is a super type of the type T of the referent. - -
-

-Two type arguments are provably distinct if neither of the arguments is a type variable or wildcard, and the two arguments are not the same type. - -


-

- Discussion -

- - The relationship of wildcards to established type theory is an interesting one, which we briefly allude to here.

- -Wildcards are a restricted form of existential types. Given a generic type declaration G<T extends B>, G<?> is roughly analogous to Some X <: B. G<X>.

- -Readers interested in a more comprehensive discussion should refer to On Variance-Based Subtyping for Parametric Types by Atsushi Igarashi and Mirko Viroli, in the proceedings of the 16th European Conference on Object Oriented Programming (ECOOP 2002).

- -Wildcards differ in certain details from the constructs described in the aforementioned paper, in particular in the use of capture conversion (§5.1.10) ratther than the close operation described by Igarashi and Viroli. For a formal account of wildcards, see Wild FJ by Mads Torgersen, Erik Ernst and Christian Plesner Hansen, in the 12th workshop on Foundations of Object Oriented Programming (FOOL 2005).

- - Historically, wildcards are a direct descendant of the work by Atsushi Igarashi and Mirko Viroli. This work itself builds upon earlier work by Kresten Thorup and Mads Torgersen ("Unifying Genericity", ECOOP 99), as well as a long tradition of work on declaration based variance that goes back to Pierre America's work on POOL (OOPSLA 89)

-


- -

- - -

4.5.1.1 Type Argument Containment and Equivalence

- -A type argument TA1 is said to contain another type argument TA2, written TA2 <= TA1, if the set of types denoted by TA2 is provably a subset of the set of types denoted by TA1 under the following rules (where <: denotes subtyping (§4.10)):

- -

- -

4.5.2 Members and Constructors of Parameterized Types

- -Let C be a class or interface declaration with formal type parameters A1,...,An, and let C<T1,...,Tn> be an invocation of C, where, for 1in, Ti are types (rather than wildcards). Then:

- -

-If any of the type arguments to a parameterized type are wildcards, the type of its members and constructors is undefined.

- -


-

- Discussion -

- -

This is of no consequence, as it is impossible to access a member of a parameterized type without performing capture conversion (§5.1.10), and it is impossible to use a wildcard type after the keyword new in a class instance creation expression

-


- - - -

4.6 Type Erasure

- -Type erasure is a mapping from types (possibly including parameterized types and type variables) to types (that are never parameterized types or type variables). We write |T| for the erasure of type T. The erasure mapping is defined as follows.

- -

-The erasure of a method signature s is a signature consisting of the same name as s, and the erasures of all the formal parameter types given in s.

- - -

4.7 Reifiable Types

- -Because some type information is erased during compilation, not all types are available at run time. Types that are completely available at run time are known as reifiable types. A type is reifiable if and only if one of the following holds:

-

- -
-

- Discussion -

- -

- The decision not to make all generic types reifiable is one of the most crucial, and controversial design decisions involving the language's type system.

- -Ultimately, the most important motivation for this decision is compatibility with existing code.

- -Naively, the addition of new constructs such as genericity has no implications for pre-existing code. The programming language per se, is compatible with earlier versions as long as every program written in the previous versions retains its meaning in the new version. However, this notion, which may be termed language compatibility, is of purely theoretical interest. Real programs (even trivial ones, such as "Hello World") are composed of several compilation units, some of which are provided by the Java platform (such as elements of java.lang or java.util).

- -In practice then, the minimum requirement is platform compatibillity - that any program written for the prior version of the platform continues to function unchanged in the new platform.

- -One way to provide platform compatibillity is to leave existing platform functionality unchanged, only adding new functionality. For example, rather than modify the existing Collections hierarchy in java.util, one might introduce a new library utilizing genericity.

- -The disadvantages of such a scheme is that it is extremely difficult for pre-existing clients of the Collection library to migrate to the new library. Collections are used to exchange data between independently developed modules; if a vendor decides to switch to the new, generic, library, that vendor must also distribute two versions of their code, to be compatible with their clients. Libraries that are dependent on other vendors code cannot be modified to use genericity until the supplier's library is updated. If two modules are mutually dependent, the changes must be made simultaneously.

- -Clearly, platform compatibility, as outlined above, does not provide a realistic path for adoption of a pervasive new feature such as genericity. Therefore, the design of the generic type system seeks to support migration compatibility. Migration compatibiliy allows the evolution of existing code to take advantage of generics without imposing dependencies between independently developed software modules.

- -The price of migration compatibility is that a full and sound reification of the generic type system is not possible, at least while the migration is taking place.

-


- - - -

4.8 Raw Types

- -To facilitate interfacing with non-generic legacy code, it is also possible to use as a type the erasure (§4.6) of a parameterized type (§4.5). Such a type is called a raw type.

- -

- -

- -

- -More precisely, a raw type is define to be either:

-

- -
-

- Discussion -

- - The latter point may not be immediately self evident. Presenting for your consideration, then, the following example:

-

class Outer<T>{
-        T t;
-        class Inner {
-                T setOuterT(T t1) {t = t1;return t;}
-        }
-}
-
- - The type of the member(s) of Inner depends on the type parameter of Outer. If Outer is raw, Inner must be treated as raw as well, as their is no valid binding for T. -

-This rule applies only to type members that are not inherited. Inherited type members that depend on type variables will be inherited as raw types as a consequence of the rule that the supertypes of a raw type are erased, described later in this section.

-


- -

- -


-

- Discussion -

- - Another implication of the rules above is that a generic inner class of a raw type can itself only be used as a raw type:

-

class Outer<T>{
-        class Inner<S> {
-                S s;
-        }
-}
-
-it is not possible to access Inner as partially raw type (a "rare" type) -
Outer.Inner<Double> x = null; // illegal
-Double d = x.s;
-
-because Outer itself is raw, so are all its inner classes, including Inner, and so it is not possible to pass any type parameters to it.

-


- -

- -The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

- -It is a compile-time error to attempt to use a type member of a parameterized type as a raw type.

- -


-

- Discussion -

- - This means that the ban on "rare" types extends to the case where the qualifying type is parameterized, but we attempt to use the inner class as a raw type:

-

Outer<Integer>.Inner x = null; // illegal
-
-This is the opposite of the case we discussed above. There is no practical justification for this half baked type. In legacy code, no type parameters are used. In non-legacy code, we should use the generic types correctly and pass all the required actual type parameters.

-


- -
-

- Discussion -

- - Variables of a raw type can be assigned from values of any of the type's parametric instances.

- -For instance, it is possible to assign a Vector<String> to a Vector, based on the subtyping rules (§4.10.2).

- - The reverse assignment from Vector to Vector<String> is unsafe (since the raw vector might have had a different element type), but is still permitted using unchecked conversion (§5.1.9) in order to enable interfacing with legacy code. In this case, a compiler will issue an unchecked warning.

-


- -The superclasses (respectively, superinterfaces) of a raw type are the erasures of the superclasses (superinterfaces) of any of its parameterized invocations.

- -The type of a constructor (§8.8), instance method (§8.8, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the generic declaration corresponding to C. The type of a static member of a raw type C is the same as its type in the generic declaration corresponding to C.

- -It is a compile-time error to pass actual type parameters to a non-static type member of a raw type that is not inherited from its superclasses or superinterfaces.

- -To make sure that potential violations of the typing rules are always flagged, some accesses to members of a raw type will result in warning messages. The rules for generating warnings when accessing members or constructors of raw types are as follows:

-

-No unchecked warning is required for a method call when the argument types do not change (even if the result type and/or throws clause changes), for reading from a field, or for a class instance creation of a raw type.

- -The supertype of a class may be a raw type. Member accesses for the class are treated as normal, and member accesses for the supertype are treated as for raw types. In the constructor of the class, calls to super are treated as method calls on a raw type.

-


-

-Discussion -

- - Example: Raw types.

-

class Cell<E>
-  E value;
-  Cell (E v) { value=v; }
-  A get() { return value; }
-  void set(E v) { value=v; }
-}
-Cell x = new Cell<String>("abc");
-x.value;          // OK, has type Object
-x.get();          // OK, has type Object
-x.set("def");     // unchecked warning
-
-
-

-


-

- Discussion -

- - For example,

-

import java.util.*;
-
-class NonGeneric {
-
-    Collection<Number> myNumbers(){return null;}
-}
-abstract class RawMembers<T> extends NonGeneric implements Collection<String> {
-    static Collection<NonGeneric> cng = 
-                                                                                new ArrayList<NonGeneric>();
-
-    public static void main(String[] args) {
-                RawMembers rw = null;
-                Collection<Number> cn = rw.myNumbers(); // ok
-                Iterator<String> is = rw.iterator(); // unchecked warning
-                Collection<NonGeneric> cnn = rw.cng; // ok - static member
-    }
-}
-
-

-RawMembers<T> inherits the method

-

Iterator<String> iterator()
-
-from the Collection<String> superinterface. However, the type RawMembers inherits iterator() from the erasure of its superinterface, which means that the return type of the member iterator() is the erasure of Iterator<<String>, Iterator. As a result, the attempt to assign to rw.iterator() requires an unchecked conversion (§5.1.9) from Iterator to Iterator<String>, causing an unchecked warning to be issued.

- -In contrast, the static member cng retains its full parameterized type even when accessed through a object of raw type (note that access to a static member through an instance is considered bad style and is to be discouraged). The member myNumbers is inherited from the NonGeneric (whose erasure is also NonGeneric) and so retains its full parameterized type.

-


- -

-


-

- Discussion -

- -

- Raw types are closly related to wildcards. Both are based on existential types. Raw types can be thought of as wildcards whose type rules are deliberately unsound, to accommodate interaction with legacy code.

- -Historically, raw types preceded wildcards; they were first introduced in GJ, and described in the paper Making the future safe for the past: Adding Genericity to the Java Programming Language by Gilad Bracha, Martin Odersky, David Stoutamire, and Philip Wadler, in Proc. of the ACM Conf. on Object-Oriented Programming, Systems, Languages and Applications, (OOPSLA 98) October 1998.

-


- -

- -

- - -

4.9 Intersection Types

- -An intersection type takes the form T1 & ... & Tn, n>0, where Ti, 1in, are type expressions. Intersection types arise in the processes of capture conversion (§5.1.10) and type inference (§15.12.2.7). It is not possible to write an intersection type directly as part of a program; no syntax supports this. The values of an intersection type are those objects that are values of all of the types Ti, for 1in.

- -The members of an intersection type T1 & ... & Tn are determined as follows:

-

- -

-


-

- Discussion -

- - It is worth dwelling upon the distinction between intersection types and the bounds of type variables. Every type variable bound induces an intersection type. This intersection type is often trivial (i.e., consists of a single type).

- -The form of a bound is restricted (only the first element may be a class or type variable, and only one type variable may appear in the bound) to preclude certain awkward situations coming into existence. However, capture conversion can lead to the creation of type variables whose bounds are more general (e.g., array types).

-


- - - -

4.10 Subtyping

- -The subtype and supertype relations are binary relations on types. The supertypes of a type are obtained by reflexive and transitive closure over the direct supertype relation, written S >1 T, which is defined by rules given later in this section. We write S :> T to indicate that the supertype relation holds between S and T. S is a proper supertype of T, written T < S, if S :> T and S T.

- -The subtypes of a type T are all types U such that T is a supertype of U, and the null type. We write T <: S to indicate that that the subtype relation holds between types T and S. T is a proper subtype of S, written T < S, if T <:S and S T. T is a direct subtype of S, written T <1 S, if S >1 T.

- -Subtyping does not extend through generic types: T <: U does not imply that C<T> <: C<U>.

- -

- - -

4.10.1 Subtyping among Primitive Types

- -The following rules define the direct supertype relation among the primitive types:

- -

-double >1 float
-float >1 long
-long >1 int
-int >1 char
-int >1 short
-short >1 byte -
-

- - -

4.10.2 Subtyping among Class and Interface Types

- -Let C be a type declaration (§4.12.6, §8.1, §9.1) with zero or more type parameters (§4.4) F1, ..., Fn which have corresponding bounds B1, ..., Bn. That type declaration defines a set of parameterized types (§4.5) C2 <T1,...,Tn>, where each argument type Ti ranges over all types that are subtypes of all types listed in the corresponding bound. That is, for each bound type Si in Bi, Ti is a subtype of Si[ F1 := T1, ..., Fn := Tn].

- -Given a type declaration for C<F1,...,Fn>, the direct supertypes of the parameterized type (§4.5) C<F1,...,Fn> are all of the following:

-

-The direct supertypes of the type C<T1,...,Tn> , where Ti,1in, is a type, are D<U1 theta, ..., Uk theta>, where

-

-The direct supertypes of the type C<R1,...,Rn> , where at least one of the Ri, 1in, is a wildcard type argument, are the direct supertypes of C<X1,...,Xn>, where

- -C<X1,...,Xn> is the result of applying capture conversion (§5.1.10) to C<R1,...,Rn>.

- -

- -The direct supertypes of an intersection type (§4.9) T1 & ... & Tn, are Ti, 1in.

- -The direct supertypes of a type variable (§4.4) are the types listed in its bound.

- -The direct supertypes of the null type are all reference types other than the null type itself.

- -In addition to the above rules, a type variable is a direct supertype of its lower bound.

- - -

4.10.3 Subtyping among Array Types

- -The following rules define the direct subtype relation among array types:

-

- -

4.11 Where Types Are Used

- -Types are used when they appear in declarations or in certain expressions.

- -

The following code fragment contains one or more instances of most kinds of usage of a type:

-
import java.util.Random;
-class MiscMath<T extends Number>{
-        int divisor;
-        MiscMath(int divisor) {
-                this.divisor = divisor;
-        }
-        float ratio(long l) {
-                try {
-                        l /= divisor;
-                } catch (Exception e) {
-                        if (e instanceof ArithmeticException)
-                                l = Long.MAX_VALUE;
-                        else
-                                l = 0;
-                }
-                return (float)l;
-        }
-        double gausser() {
-                Random r = new Random();
-                double[] val = new double[2];
-                val[0] = r.nextGaussian();
-                val[1] = r.nextGaussian();
-                return (val[0] + val[1]) / 2;
-
    }
-   Collection<Number> fromArray(Number[] na) {
-           Collection<Number> cn = new ArrayList<Number>();
-           for (Number n : na) {
-                   cn.add(n)
-           }
-           return cn;
-   }
-   void <S> loop(S s){ this.<S>loop(s);}
-           
-
-

-

}
-
-In this example, types are used in declarations of the following:

-

-and in expressions of the following kinds:

-

-. Types are also used as arguments to parameterized types; here the type Number is used as an argument in the parameterized type Collection<Number>.

- - -

4.12 Variables

- -A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3). A variable's value is changed by an assignment (§15.26) or by a prefix or postfix ++ (increment) or -- (decrement) operator (§15.14.2, §15.14.3, §15.15.1, §15.15.2).

- -Compatibility of the value of a variable with its type is guaranteed by the design of the Java programming language, as long as a program does not give rise to unchecked warnings (§4.12.2.1). Default values are compatible (§4.12.5) and all assignments to a variable are checked for assignment compatibility (§5.2), usually at compile time, but, in a single case involving arrays, a run-time check is made (§10.10).

- - -

4.12.1 Variables of Primitive Type

- -A variable of a primitive type always holds a value of that exact primitive type.

- - -

4.12.2 Variables of Reference Type

- -A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T. A variable of an interface type can hold a null reference or a reference to any instance of any class that implements the interface.

- -

-


-

- Discussion -

- - Note that a variable is not guaranteed to always refer to a subtype of its declared type, but only to subclasses or subinterfaces of the declared type. This is due to the possibility of heap pollution discussed below.

- -


-

- -If T is a primitive type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of T"; if T is a reference type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of S" such that type S is a subclass or subinterface of type T. In addition, a variable of type Object[] can hold an array of any reference type. A variable of type Object can hold a null reference or a reference to any object, whether class instance or array.

- - -

4.12.2.1 Heap Pollution

- -It is possible that a variable of a parameterized type refers to an object that is not of that parameterized type. This situation is known as heap pollution. This situation can only occur if the program performed some operation that would give rise to an unchecked warning at compile-time.

-


-

-Discussion -

- - For example, the code:

-

List l = new ArrayList<Number>();
-List<String> ls = l; // unchecked warning
-
- - gives rise to an unchecked warning, because it is not possible to ascertain, either at compile-time (within the limits of the compile-time type checking rules) or at run-time, whether the variable l does indeed refer to a List<String>.

- -If the code above is executed, heap pollution arises, as the variable ls, declared to be a List<String>, refers to a value that is not in fact a List<String>.

- -The problem cannot be identified at run-time because type variables are not reified, and thus instances do not carry any information at run-time regarding the actual type parameters used to create them.

- -In a simple example as given above, it may appear that it should be straightforward to identify the situation at compile-time and give a compilation error. However, in the general (and typical) case, the value of the variable l may be the result of an invocation of a separately compiled method, or its value may depend upon arbitrary control flow.

- -The code above is therefore very atypical, and indeed very bad style.

- -Assignment from a value of a raw type to a variable of a parameterized type should only be used when combining legacy code which does not make use of parameterized types with more modern code that does.

- -If no operation that requires an unchecked warning to be issued takes place, heap pollution cannot occur. Note that this does not imply that heap pollution only occurs if an unchecked warning actually occurred. It is possible to run a program where some of the binaries were compiled by a compiler for an older version of the Java programming language, or by a compiler that allows the unchecked warnings to suppressed. This practice is unhealthy at best.

- -Conversely, it is possible that despite executing code that could (and perhaps did) give rise to an unchecked warning, no heap pollution takes place. Indeed, good programming practice requires that the programmer satisfy herself that despite any unchecked warning, the code is correct and heap pollution will not occur.

-


- -

- -The variable will always refer to an object that is an instance of a class that implements the parameterized type.

- -

-


-

- Discussion -

- - For instance, the value of l in the example above is always a List.

-


- -

- - -

4.12.3 Kinds of Variables

- -There are seven kinds of variables:

-

    - -
  1. A class variable is a field declared using the keyword static within a class declaration (§8.3.1.1), or with or without the keyword static within an interface declaration (§9.3). A class variable is created when its class or interface is prepared (§12.3.2) and is initialized to a default value (§4.12.5). The class variable effectively ceases to exist when its class or interface is unloaded (§12.7). - -
  2. An instance variable is a field declared within a class declaration without using the keyword static (§8.3.1.1). If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.12.5) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.4). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed. - -
  3. Array components are unnamed variables that are created and initialized to default values (§4.12.5) whenever a new object that is an array is created (§15.10). The array components effectively cease to exist when the array is no longer referenced. See §10 for a description of arrays. - -
  4. Method parameters (§8.4.1) name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked (§15.12). The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete. - -
  5. Constructor parameters (§8.8.1) name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression (§15.9) or explicit constructor invocation (§8.8.7) invokes that constructor. The new variable is initialized with the corresponding argument value from the creation expression or constructor invocation. The constructor parameter effectively ceases to exist when the execution of the body of the constructor is complete. - -
  6. An exception-handler parameter is created each time an exception is caught by a catch clause of a try statement (§14.20). The new variable is initialized with the actual object associated with the exception (§11.3, §14.18). The exception-handler parameter effectively ceases to exist when execution of the block associated with the catch clause is complete. - -
  7. Local variables are declared by local variable declaration statements (§14.4). Whenever the flow of control enters a block (§14.2) or for statement (§14.14), a new variable is created for each local variable declared in a local variable declaration statement immediately contained within that block or for statement. A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (§16) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or for statement is complete. -
-

-Were it not for one exceptional situation, a local variable could always be regarded as being created when its local variable declaration statement is executed. The exceptional situation involves the switch statement (§14.11), where it is possible for control to enter a block but bypass execution of a local variable declaration statement. Because of the restrictions imposed by the rules of definite assignment (§16), however, the local variable declared by such a bypassed local variable declaration statement cannot be used before it has been definitely assigned a value by an assignment expression (§15.26). - -

The following example contains several different kinds of variables: -

-class Point {
-        static int numPoints;                   // numPoints is a class variable
-        int x, y;                               // x and y are instance variables
-        int[] w = new int[10];                  // w[0] is an array component
-        int setX(int x) {                       // x is a method parameter
-                int oldx = this.x;              // oldx is a local variable
-                this.x = x;
-                return oldx;
-        }
-}
-
- -

4.12.4 final Variables

- -A variable can be declared final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

- -A blank final is a final variable whose declaration lacks an initializer.

- -Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object. This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.

- -

Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.

- -

In the example:

-
class Point {
-        int x, y;
-        int useCount;
-        Point(int x, int y) { this.x = x; this.y = y; }
-        final static Point origin = new Point(0, 0);
-}
-
-the class Point declares a final class variable origin. The origin variable holds a reference to an object that is an instance of class Point whose coordinates are (0, 0). The value of the variable Point.origin can never change, so it always refers to the same Point object, the one created by its initializer. However, an operation on this Point object might change its state-for example, modifying its useCount or even, misleadingly, its x or y coordinate.

- -We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

- -

- - -

4.12.5 Initial Values of Variables

- -Every variable in a program must have a value before its value is used:

-

-The example program:

-

class Point {
-        static int npoints;
-        int x, y;
-        Point root;
-}
-class Test {
-        public static void main(String[] args) {
-                System.out.println("npoints=" + Point.npoints);
-                Point p = new Point();
-                System.out.println("p.x=" + p.x + ", p.y=" + p.y);
-                System.out.println("p.root=" + p.root);
-        }
-}
-
-prints:

-

npoints=0
-p.x=0, p.y=0
-p.root=null
-
-illustrating the default initialization of npoints, which occurs when the class Point is prepared (§12.3.2), and the default initialization of x, y, and root, which occurs when a new Point is instantiated. See §12 for a full description of all aspects of loading, linking, and initialization of classes and interfaces, plus a description of the instantiation of classes to make new class instances.

- - -

4.12.6 Types, Classes, and Interfaces

- -In the Java programming language, every variable and every expression has a type that can be determined at compile time. The type may be a primitive type or a reference type. Reference types include class types and interface types. Reference types are introduced by type declarations, which include class declarations (§8.1) and interface declarations (§9.1). We often use the term type to refer to either a class or an interface.

- -Every object belongs to some particular class: the class that was mentioned in the creation expression that produced the object, the class whose Class object was used to invoke a reflective method to produce the object, or the String class for objects implicitly created by the string concatenation operator + (§15.18.1). This class is called the class of the object. (Arrays also have a class, as described at the end of this section.) An object is said to be an instance of its class and of all superclasses of its class.

- -Sometimes a variable or expression is said to have a "run-time type". This refers to the class of the object referred to by the value of the variable or expression at run time, assuming that the value is not null.

- -The compile time type of a variable is always declared, and the compile time type of an expression can be deduced at compile time. The compile time type limits the possible values that the variable can hold or the expression can produce at run time. If a run-time value is a reference that is not null, it refers to an object or array that has a class, and that class will necessarily be compatible with the compile-time type.

- -Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (§8.1.5) that interface.

- -

Here is an example of creating new objects and of the distinction between the type of a variable and the class of an object:

-
public interface Colorable {
-        void setColor(byte r, byte g, byte b);
-}
-class Point { int x, y; }
-class ColoredPoint extends Point implements Colorable {
-        byte r, g, b;
-        public void setColor(byte rv, byte gv, byte bv) {
-                r = rv; g = gv; b = bv;
-        }
-}
-class Test {
-        public static void main(String[] args) {
-                Point p = new Point();
-                ColoredPoint cp = new ColoredPoint();
-                p = cp;
-                Colorable c = cp;
-        }
-}
-
-In this example:

-

- -

-


-

- Discussion -

- - Note that an expression such as new Colorable() is not valid because it is not possible to create an instance of an interface, only of a class.

- -

-


- -Every array also has a class; the method getClass, when invoked for an array object, will return a class object (of class Class) that represents the class of the array.

- -

The classes for arrays have strange names that are not valid identifiers; for example, the class for an array of int components has the name "[I" and so the value of the expression:

-
new int[10].getClass().getName()
-
-is the string "[I"; see the specification of Class.getName for details.

- - -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- -

- - -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - - Names - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 6

- -

Names

-

- -Names are used to refer to entities declared in a program. A declared entity (§6.1) is a package, class type (normal or enum), interface type (normal or annotation type), member (class, interface, field, or method) of a reference type, type parameter (of a class, interface, method or constructor) (§4.4), parameter (to a method, constructor, or exception handler), or local variable.

- -Names in programs are either simple, consisting of a single identifier, or qualified, consisting of a sequence of identifiers separated by "." tokens (§6.2).

- -Every declaration that introduces a name has a scope (§6.3), which is the part of the program text within which the declared entity can be referred to by a simple name.

- -Packages and reference types (that is, class types, interface types, and array types) have members (§6.4). A member can be referred to using a qualified name N.x, where N is a simple or qualified name and x is an identifier. If N names a package, then x is a member of that package, which is either a class or interface type or a subpackage. If N names a reference type or a variable of a reference type, then x names a member of that type, which is either a class, an interface, a field, or a method.

- -In determining the meaning of a name (§6.5), the context of the occurrence is used to disambiguate among packages, types, variables, and methods with the same name.

- -Access control (§6.6) can be specified in a class, interface, method, or field declaration to control when access to a member is allowed. Access is a different concept from scope; access specifies the part of the program text within which the declared entity can be referred to by a qualified name, a field access expression (§15.11), or a method invocation expression (§15.12) in which the method is not specified by a simple name. The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are public, protected, and private.

- -Fully qualified and canonical names (§6.7) and naming conventions (§6.8) are also discussed in this chapter.

- -The name of a field, parameter, or local variable may be used as an expression (§15.14.2). The name of a method may appear in an expression only as part of a method invocation expression (§15.12). The name of a class or interface type may appear in an expression only as part of a class literal (§15.8.2), a qualified this expression (§15.8.4), a class instance creation expression (§15.9), an array creation expression (§15.10), a cast expression (§15.16), an instanceof expression (§15.20.2), an enum constant (§8.9), or as part of a qualified name for a field or method. The name of a package may appear in an expression only as part of a qualified name for a class or interface type.

- - -

6.1 Declarations

- -A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:

-

-Constructors (§8.8) are also introduced by declarations, but use the name of the class in which they are declared rather than introducing a new name.

- - -

6.2 Names and Identifiers

- -A name is used to refer to an entity declared in a program.

- -There are two forms of names: simple names and qualified names. A simple name is a single identifier. A qualified name consists of a name, a "." token, and an identifier.

- -In determining the meaning of a name (§6.5), the context in which the name appears is taken into account. The rules of §6.5 distinguish among contexts where a name must denote (refer to) a package (§6.5.3), a type (§6.5.5), a variable or value in an expression (§6.5.6), or a method (§6.5.7).

- -Not all identifiers in programs are a part of a name. Identifiers are also used in the following situations:

-

-In the example:

-

class Test {
-        public static void main(String[] args) {
-                Class c = System.out.getClass();
-                System.out.println(c.toString().length() +
-                                args[0].length() + args.length);
-        }
-}
-
-the identifiers Test, main, and the first occurrences of args and c are not names; rather, they are used in declarations to specify the names of the declared entities. The names String, Class, System.out.getClass, System.out.println, c.toString, args, and args.length appear in the example. The first occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.12). The second occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.12).

- -

The identifiers used in labeled statements and their associated break and continue statements are completely separate from those used in declarations. Thus, the following code is valid:

-
class TestString {
-        char[] value;
-        int offset, count;
-        int indexOf(TestString str, int fromIndex) {
-                char[] v1 = value, v2 = str.value;
-                int max = offset + (count - str.count);
-                int start = offset + ((fromIndex < 0) ? 0 : fromIndex);
-        i:
-                for (int i = start; i <= max; i++)
-                {
-                        int n = str.count, j = i, k = str.offset;
-                        while (n-- != 0) {
-                                if (v1[j++] != v2[k++])
-                                        continue i;
-                        } 
-                        return i - offset;
-                }
-                return -1;
-        }
-}
-
-This code was taken from a version of the class String and its method indexOf, where the label was originally called test. Changing the label to have the same name as the local variable i does not obscure (§6.3.2) the label in the scope of the declaration of i. The identifier max could also have been used as the statement label; the label would not obscure the local variable max within the labeled statement.

- - -

6.3 Scope of a Declaration

- -The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name (provided it is visible (§6.3.1)). A declaration is said to be in scope at a particular point in a program if and only if the declaration's scope includes that point.

- -The scoping rules for various constructs are given in the sections that describe those constructs. For convenience, the rules are repeated here:

- - The scope of the declaration of an observable (§7.4.3) top level package is all observable compilation units (§7.3). The declaration of a package that is not observable is never in scope. Subpackage declarations are never in scope.

- -The scope of a type imported by a single-type-import declaration (§7.5.1) or a type-import-on-demand declaration (§7.5.2) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.

- -The scope of a member imported by a single-static-import declaration (§7.5.3) or a static-import-on-demand declaration (§7.5.4) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.

- -The scope of a top level type is all type declarations in the package in which the top level type is declared.

- -The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, including any nested type declarations.

- -The scope of the declaration of a member m declared in or inherited by an interface type I is the entire body of I, including any nested type declarations.

- -The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.

- -The scope of an interface's type parameter is the entire declaration of the interface including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

- -The scope of a method's type parameter is the entire declaration of the method, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

- -The scope of a constructor's type parameter is the entire declaration of the constructor, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

- -The scope of a local variable declaration in a block (§14.4.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

- -The scope of a local class immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration. The scope of a local class immediately enclosed by in a switch block statement group (§14.11)is the rest of the immediately enclosing switch block statement group, including its own class declaration.

- -The scope of a local variable declared in the forInit part of a basic for statement (§14.14) includes all of the following:

-

-The scope of a local variable declared in the FormalParameter part of an enhanced for statement (§14.14) is the contained Statement

- -The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (§14.20) is the entire block associated with the catch.

- -These rules imply that declarations of class and interface types need not appear before uses of the types.

- -

In the example:

-
package points;
-class Point {
-        int x, y;
-        PointList list;
-        Point next;
-}
-class PointList {
-        Point first;
-}
-
- -

the use of PointList in class Point is correct, because the scope of the class declaration PointList includes both class Point and class PointList, as well as any other type declarations in other compilation units of package points.

- - -

6.3.1 Shadowing Declarations

- -Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.

- -A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d.

- -A declaration d of a field, local variable, method parameter, constructor parameter or exception handler parameter named n shadows the declarations of any other fields, local variables, method parameters, constructor parameters or exception handler parameters named n that are in scope at the point where d occurs throughout the scope of d.

- -A declaration d of a method named n shadows the declarations of any other methods named n that are in an enclosing scope at the point where d occurs throughout the scope of d.

- -A package declaration never shadows any other declaration.

- -A single-type-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

-

-throughout c.

- -A single-static-import declaration d in a compilation unit c of package p that imports a field named n shadows the declaration of any static field named n imported by a static-import-on-demand declaration in c, throughout c.

- -A single-static-import declaration d in a compilation unit c of package p that imports a method named n with signature s shadows the declaration of any static method named n with signature s imported by a static-import-on-demand declaration in c, throughout c.

- -A single-static-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

-

-throughout c.

- -A type-import-on-demand declaration never causes any other declaration to be shadowed.

- -A static-import-on-demand declaration never causes any other declaration to be shadowed.

- -A declaration d is said to be visible at point p in a program if the scope of d includes p, and d is not shadowed by any other declaration at p. When the program point we are discussing is clear from context, we will often simply say that a declaration is visible.

- -

Note that shadowing is distinct from hiding (§8.3, §8.4.8.2, §8.5, §9.3, §9.5). Hiding, in the technical sense defined in this specification, applies only to members which would otherwise be inherited but are not because of a declaration in a subclass. Shadowing is also distinct from obscuring (§6.3.2).

- -

Here is an example of shadowing of a field declaration by a local variable declaration:

-
class Test {
-        static int x = 1;
-        public static void main(String[] args) {
-                int x = 0;
-                System.out.print("x=" + x);
-                System.out.println(", Test.x=" + Test.x);
-        }
-}
-
-produces the output:

-

x=0, Test.x=1
-
-This example declares:

-

-

Since the scope of a class variable includes the entire body of the class (§8.2) the class variable x would normally be available throughout the entire body of the method main. In this example, however, the class variable x is shadowed within the body of the method main by the declaration of the local variable x.

- -

A local variable has as its scope the rest of the block in which it is declared (§14.4.2); in this case this is the rest of the body of the main method, namely its initializer "0" and the invocations of print and println.

- -

This means that:

- - - -

The following example illustrates the shadowing of one type declaration by another:

-
import java.util.*;
-class Vector {
-        int val[] = { 1 , 2 };
-
-

}

-class Test { - public static void main(String[] args) { - Vector v = new Vector(); - System.out.println(v.val[0]); - } -} -
-compiles and prints:

-

1
-
-using the class Vector declared here in preference to the generic (§8.1.2) class java.util.Vector that might be imported on demand.

- - -

6.3.2 Obscured Declarations

- -A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.

- -

Obscuring is distinct from shadowing (§6.3.1) and hiding (§8.3, §8.4.8.2, §8.5, §9.3, §9.5). The naming conventions of §6.8 help reduce obscuring.

- - -

6.4 Members and Inheritance

- -Packages and reference types have members.

- -

This section provides an overview of the members of packages and reference types here, as background for the discussion of qualified names and the determination of the meaning of names. For a complete description of membership, see §4.4, §4.5.2, §4.8, §4.9, §7.1, §8.2, §9.2, and §10.7.

- -

- - -

6.4.1 The Members of Type Variables, Parameterized Types, Raw Types and Intersection Types

- -The members of a type variable were specified in §4.4, the members of a parameterized type in §4.5.2, those of a raw type in §4.8, and the members of an intersection type were specified in §4.9.

- -

- - -

6.4.2 The Members of a Package

- -The members of a package (§7) are specified in §7.1. For convenience, we repeat that specification here:

- -The members of a package are its subpackages and all the top level (§7.6) class types (§8) and top level interface types (§9) declared in all the compilation units (§7.3) of the package.

- -

In general, the subpackages of a package are determined by the host system (§7.2). However, the package java always includes the subpackages lang and io and may include other subpackages. No two distinct members of the same package may have the same simple name (§7.1), but members of different packages may have the same simple name.

- -

For example, it is possible to declare a package:

-
package vector;
-public class Vector { Object[] vec; }
-
-that has as a member a public class named Vector, even though the package java.util also declares a class named Vector. These two class types are different, reflected by the fact that they have different fully qualified names (§6.7). The fully qualified name of this example Vector is vector.Vector, whereas java.util.Vector is the fully qualified name of the Vector class usually included in the Java platform. Because the package vector contains a class named Vector, it cannot also have a subpackage named Vector.

- - -

6.4.3 The Members of a Class Type

- -The members of a class type (§8.2) are classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4). Members are either declared in the type, or inherited because they are accessible members of a superclass or superinterface which are neither private nor hidden nor overridden (§8.4.8).

- -

The members of a class type are all of the following:

- -Constructors (§8.8) and type variables (§4.4) are not members.

- -

There is no restriction against a field and a method of a class type having the same simple name. Likewise, there is no restriction against a member class or member interface of a class type having the same simple name as a field or method of that class type.

- -

A class may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error (§6.5.7.2, §8.2).

- -

In the example:

-
-interface Colors {
-        int WHITE = 0, BLACK = 1;
-}
-
-interface Separates {
-        int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
-}
-
-class Test implements Colors, Separates {
-        public static void main(String[] args) {
-                System.out.println(BLACK); // compile-time error: ambiguous
-        }
-}
-
-the name BLACK in the method main is ambiguous, because class Test has two members named BLACK, one inherited from Colors and one from Separates.

- -

A class type may have two or more methods with the same simple name if the methods have signatures that are not override-equivalent (§8.4.2). Such a method member name is said to be overloaded.

- -

A class type may contain a declaration for a method with the same name and the same signature as a method that would otherwise be inherited from a superclass or superinterface. In this case, the method of the superclass or superinterface is not inherited. If the method not inherited is abstract, then the new declaration is said to implement it; if the method not inherited is not abstract, then the new declaration is said to override it.

- -

In the example:

-
class Point {
-        float x, y;
-        void move(int dx, int dy) { x += dx; y += dy; }
-        void move(float dx, float dy) { x += dx; y += dy; }
-        public String toString() { return "("+x+","+y+")"; }
-}
-
-the class Point has two members that are methods with the same name, move. The overloaded move method of class Point chosen for any particular method invocation is determined at compile time by the overloading resolution procedure given in §15.12.

- -

In this example, the members of the class Point are the float instance variables x and y declared in Point, the two declared move methods, the declared toString method, and the members that Point inherits from its implicit direct superclass Object (§4.3.2), such as the method hashCode. Note that Point does not inherit the toString method of class Object because that method is overridden by the declaration of the toString method in class Point.

- - -

6.4.4 The Members of an Interface Type

- -The members of an interface type (§9.2) may be classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4). The members of an interface are:

-

-Type variables (§4.4) are not members.

- -An interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any such field by its simple name results in a compile-time error (§6.5.6.1, §9.2).

- -

In the example:

-
interface Colors {
-        int WHITE = 0, BLACK = 1;
-}
-interface Separates {
-        int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
-}
-interface ColorsAndSeparates extends Colors, Separates {
-        int DEFAULT = BLACK;                                                                    // compile-time error: ambiguous
-}
-
-the members of the interface ColorsAndSeparates include those members inherited from Colors and those inherited from Separates, namely WHITE, BLACK (first of two), CYAN, MAGENTA, YELLOW, and BLACK (second of two). The member name BLACK is ambiguous in the interface ColorsAndSeparates.

- - -

6.4.5 The Members of an Array Type

- -The members of an array type are specified in §10.7. For convenience, we repeat that specification here.

- -The members of an array type are all of the following:

-

-

- -The example:

-

class Test {
-        public static void main(String[] args) {
-                int[] ia = new int[3];
-                int[] ib = new int[6];
-                System.out.println(ia.getClass() == ib.getClass());
-                System.out.println("ia has length=" + ia.length);
-        }
-}
-
-produces the output:

-

true
-ia has length=3
-
-This example uses the method getClass inherited from class Object and the field length. The result of the comparison of the Class objects in the first println demonstrates that all arrays whose components are of type int are instances of the same array type, which is int[].

- - -

6.5 Determining the Meaning of a Name

- -The meaning of a name depends on the context in which it is used. The determination of the meaning of a name requires three steps. First, context causes a name syntactically to fall into one of six categories: PackageName, TypeName, ExpressionName, MethodName, PackageOrTypeName, or AmbiguousName. Second, a name that is initially classified by its context as an AmbiguousName or as a PackageOrTypeName is then reclassified to be a PackageName, TypeName, or ExpressionName. Third, the resulting category then dictates the final determination of the meaning of the name (or a compilation error if the name has no meaning).

-


-PackageName:
-        Identifier
-        PackageName . Identifier
-
-TypeName:
-        Identifier
-        PackageOrTypeName . Identifier
-
-ExpressionName:
-        Identifier
-        AmbiguousName . Identifier
-
-MethodName:
-        Identifier
-        AmbiguousName . Identifier
-
-PackageOrTypeName:
-        Identifier
-        PackageOrTypeName . Identifier
-
-AmbiguousName:
-        Identifier
-        AmbiguousName . Identifier
-        
- -

The use of context helps to minimize name conflicts between entities of different kinds. Such conflicts will be rare if the naming conventions described in §6.8 are followed. Nevertheless, conflicts may arise unintentionally as types developed by different programmers or different organizations evolve. For example, types, methods, and fields may have the same name. It is always possible to distinguish between a method and a field with the same name, since the context of a use always tells whether a method is intended.

- - -

6.5.1 Syntactic Classification of a Name According to Context

- -A name is syntactically classified as a PackageName in these contexts:

-

-A name is syntactically classified as a TypeName in these contexts:

-

-

- -

- -

- -A name is syntactically classified as an ExpressionName in these contexts:

-

-A name is syntactically classified as a MethodName in these contexts:

-

-A name is syntactically classified as a PackageOrTypeName in these contexts:

-

-A name is syntactically classified as an AmbiguousName in these contexts:

-

- -

6.5.2 Reclassification of Contextually Ambiguous Names

- -An AmbiguousName is then reclassified as follows:

-

-

As an example, consider the following contrived "library code":

-
package org.rpgpoet;
-import java.util.Random;
-interface Music { Random[] wizards = new Random[4]; }
-
-and then consider this example code in another package:

-

package bazola;
-class Gabriel {
-        static int n = org.rpgpoet.Music.wizards.length;
-}
-
-First of all, the name org.rpgpoet.Music.wizards.length is classified as an ExpressionName because it functions as a PostfixExpression. Therefore, each of the names:

- -

-
org.rpgpoet.Music.wizards
-org.rpgpoet.Music
-org.rpgpoet
-org 
-
-is initially classified as an AmbiguousName. These are then reclassified:

-

- -

6.5.3 Meaning of Package Names

- -The meaning of a name classified as a PackageName is determined as follows.

- - -

6.5.3.1 Simple Package Names

- -If a package name consists of a single Identifier, then this identifier denotes a top level package named by that identifier. If no top level package of that name is in scope (§7.4.4), then a compile-time error occurs.

- - -

6.5.3.2 Qualified Package Names

- -If a package name is of the form Q.Id, then Q must also be a package name. The package name Q.Id names a package that is the member named Id within the package named by Q. If Q does not name an observable package (§7.4.3), or Id is not the simple name an observable subpackage of that package, then a compile-time error occurs.

- - -

6.5.4 Meaning of PackageOrTypeNames

- - -

6.5.4.1 Simple PackageOrTypeNames

- -If the PackageOrTypeName, Q, occurs in the scope of a type named KQ, then the PackageOrTypeName is reclassified as a TypeName.

- -Otherwise, the PackageOrTypeName is reclassified as a PackageName. The meaning of the PackageOrTypeName is the meaning of the reclassified name.

- - -

6.5.4.2 Qualified PackageOrTypeNames

- -Given a qualified PackageOrTypeName of the form Q.Id, if the type or package denoted by Q has a member type named Id, then the qualified PackageOrTypeName name is reclassified as a TypeName.

- -Otherwise, it is reclassified as a PackageName. The meaning of the qualified PackageOrTypeName is the meaning of the reclassified name.

- - -

6.5.5 Meaning of Type Names

- -The meaning of a name classified as a TypeName is determined as follows.

- - -

6.5.5.1 Simple Type Names

- -If a type name consists of a single Identifier, then the identifier must occur in the scope of exactly one visible declaration of a type with this name, or a compile-time error occurs. The meaning of the type name is that type.

- - -

6.5.5.2 Qualified Type Names

- -If a type name is of the form Q.Id, then Q must be either a type name or a package name. If Id names exactly one type that is a member of the type or package denoted by Q, then the qualified type name denotes that type. If Id does not name a member type (§8.5, §9.5) within Q, or the member type named Id within Q is not accessible (§6.6), or Id names more than one member type within Q, then a compile-time error occurs.

- -

The example:

-
package wnj.test;
-class Test {
-        public static void main(String[] args) {
-                java.util.Date date =
-                        new java.util.Date(System.currentTimeMillis());
-                System.out.println(date.toLocaleString());
-        }
-}
-
-produced the following output the first time it was run:

-

Sun Jan 21 22:56:29 1996
-
-In this example the name java.util.Date must denote a type, so we first use the procedure recursively to determine if java.util is an accessible type or a package, which it is, and then look to see if the type Date is accessible in this package.

-


-

-Discussion -

- -

- - Type names are distinct from type declaration specifiers (§4.3). A type name is always qualified by meas of another type name. In some cases, it is necessary to access an inner class that is a member of a parameterized type:

-

class GenericOuter<T extends Number> {
-        public class Inner<S extends Comparable<S>> {
-                        T getT() { return null;}
-                        S getS() { return null;}
-        }
-};
-
-GenericOuter<Integer>.Inner<Double> x1 = null;
-Integer i = x1.getT();
-Double d = x1.getS();
-
-If we accessed Inner by qualifying it with a type name, as in:

-

GenericOuter.Inner x2 = null;
-
-we would force its use as a raw type, losing type information.

-


- -

- -

- - -

6.5.6 Meaning of Expression Names

- -The meaning of a name classified as an ExpressionName is determined as follows.

- - -

6.5.6.1 Simple Expression Names

- -If an expression name consists of a single Identifier, then there must be exactly one visible declaration denoting either a local variable, parameter or field in scope at the point at which the the Identifier occurs. Otherwise, a compile-time error occurs.

- -If the declaration declares a final field, the meaning of the name is the value of that field. Otherwise, the meaning of the expression name is the variable declared by the declaration.

- -If the field is an instance variable (§8.3), the expression name must appear within the declaration of an instance method (§8.4), constructor (§8.8), instance initializer (§8.6), or instance variable initializer (§8.3.2.2). If it appears within a static method (§8.4.3.2), static initializer (§8.7), or initializer for a static variable (§8.3.2.1, §12.4.2), then a compile-time error occurs.

- -The type of the expression name is the declared type of the field, local variable or parameter after capture conversion (§5.1.10).

- -In the example:

-

class Test {
-        static int v;
-        static final int f = 3;
-        public static void main(String[] args) {
-                int i;
-                i = 1;
-                v = 2;
-                f = 33;                         // compile-time error
-                System.out.println(i + " " + v + " " + f);
-        }
-}
-
-the names used as the left-hand-sides in the assignments to i, v, and f denote the local variable i, the field v, and the value of f (not the variable f, because f is a final variable). The example therefore produces an error at compile time because the last assignment does not have a variable as its left-hand side. If the erroneous assignment is removed, the modified code can be compiled and it will produce the output:

-

1 2 3
-
- -

6.5.6.2 Qualified Expression Names

- -If an expression name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name:

-

- -

The example:

-
-class Point {
-        int x, y;
-        static int nPoints;
-}
-class Test {
-        public static void main(String[] args) {
-                int i = 0;
-                i.x++;                  // compile-time error
-                Point p = new Point();
-                p.nPoints();            // compile-time error
-        }
-}
-
-encounters two compile-time errors, because the int variable i has no members, and because nPoints is not a method of class Point.

- -


-

-Discussion -

- - -

- - Note that expression names may be qualified by type names, but not by types in general. A consequence is that it is not possible to access a class variable through a parameterized type

-

class Foo<T> {
-        public static int classVar = 42;
-}
-Foo<String>.classVar = 91; // illegal
-
-Instead, one writes

-

Foo.classVar = 91;
-
-This does not restrict the language in any meaningful way. Type parameters may not be used in the types of static variables, and so the actual parameters of a parameterized type can never influence the type of a static variable. Therefore, no expressive power is lost. Technically, the type name Foo above is a raw type, but this use of raw types is harmless, and does not give rise to warnings

-


- -

- - -

6.5.7 Meaning of Method Names

- -A MethodName can appear only in a method invocation expression (§15.12) or as an element name in an element-value pair (§9.7). The meaning of a name classified as a MethodName is determined as follows.

- - -

6.5.7.1 Simple Method Names

- -A simple method name may appear as the element name in an element-value pair. The Identifier in an ElementValuePair must be the simple name of one of the elements of the annotation type identified by TypeName in the containing annotation. Otherwise, a compile-time error occurs. (In other words, the identifier in an element-value pair must also be a method name in the interface identified by TypeName.)

- -Otherwise, a simple method name necessarily appears in the context of a method invocation expression. In that case, if a method name consists of a single Identifier, then Identifier is the method name to be used for method invocation. The Identifier must name at least one visible (§6.3.1) method that is in scope at the point where the Identifier appear or a method imported by a single-static-import declaration (§7.5.3) or static-import-on-demand declaration (§7.5.4) within the compilation unit within which the Identifier appears.

- -See §15.12 for further discussion of the interpretation of simple method names in method invocation expressions.

- - -

6.5.7.2 Qualified Method Names

- -A qualified method name can only appear in the context of a method invocation expression. If a method name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name. If Q is a package name, then a compile-time error occurs. Otherwise, Id is the method name to be used for method invocation. If Q is a type name, then Id must name at least one static method of the type Q. If Q is an expression name, then let T be the type of the expression Q; Id must name at least one method of the type T. See §15.12 for further discussion of the interpretation of qualified method names in method invocation expressions.

- -


-

- Discussion -

-

- - Like expression names, method names may be qualified by type names, but not by types in general. The implications are similar to those for expression names as discussed in §6.5.6.2.

-


- - -

- - -

6.6 Access Control

- -The Java programming language provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. If access is permitted, then the accessed entity is said to be accessible.

- -Note that accessibility is a static property that can be determined at compile time; it depends only on types and declaration modifiers. Qualified names are a means of access to members of packages and reference types; related means of access include field access expressions (§15.11) and method invocation expressions (§15.12). All three are syntactically similar in that a "." token appears, preceded by some indication of a package, type, or expression having a type and followed by an Identifier that names a member of the package or type. These are collectively known as constructs for qualified access.

- -Access control applies to qualified access and to the invocation of constructors by class instance creation expressions (§15.9) and explicit constructor invocations (§8.8.7.1). Accessibility also effects inheritance of class members (§8.2), including hiding and method overriding (§8.4.8.1).

- - -

6.6.1 Determining Accessibility

- - -

6.6.2 Details on protected Access

- -A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

- - -

6.6.2.1 Access to a protected Member

- -Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:

-

- -

6.6.2.2 Qualified Access to a protected Constructor

- -Let C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. Then:

-

- -

6.6.3 An Example of Access Control

- -For examples of access control, consider the two compilation units:

-

package points;
-class PointVec { Point[] vec; }
-
-and:

-

package points;
-public class Point {
-        protected int x, y;
-        public void move(int dx, int dy) { x += dx; y += dy; }
-        public int getX() { return x; }
-        public int getY() { return y; }
-}
-
-which declare two class types in the package points:

-

-See §6.6.7 for an example of how the protected access modifier limits access.

- - -

6.6.4 Example: Access to public and Non-public Classes

- -If a class lacks the public modifier, access to the class declaration is limited to the package in which it is declared (§6.6). In the example:

-

package points;
-public class Point {
-        public int x, y;
-        public void move(int dx, int dy) { x += dx; y += dy; }
-
-

}

-class PointList { - Point next, prev; -} -
-two classes are declared in the compilation unit. The class Point is available outside the package points, while the class PointList is available for access only within the package.

- -

Thus a compilation unit in another package can access points.Point, either by using its fully qualified name:

-
package pointsUser;
-class Test {
-        public static void main(String[] args) {
-                points.Point p = new points.Point();
-                System.out.println(p.x + " " + p.y);
-        }
-}
-
-or by using a single-type-import declaration (§7.5.1) that mentions the fully qualified name, so that the simple name may be used thereafter:

-

package pointsUser;
-import points.Point;
-class Test {
-        public static void main(String[] args) {
-                Point p = new Point();
-                System.out.println(p.x + " " + p.y);
-        }}
-
-However, this compilation unit cannot use or import points.PointList, which is not declared public and is therefore inaccessible outside package points.

- - -

6.6.5 Example: Default-Access Fields, Methods, and Constructors

- -If none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package.

- -

If a public class has a method or constructor with default access, then this method or constructor is not accessible to or inherited by a subclass declared outside this package.

- -

For example, if we have:

-
package points;
-public class Point {
-        public int x, y;
-        void move(int dx, int dy) { x += dx; y += dy; }
-        public void moveAlso(int dx, int dy) { move(dx, dy); }
-}
-
-then a subclass in another package may declare an unrelated move method, with the same signature (§8.4.2) and return type. Because the original move method is not accessible from package morepoints, super may not be used:

-

package morepoints;
-public class PlusPoint extends points.Point {
-        public void move(int dx, int dy) {
-                super.move(dx, dy);                                                             // compile-time error
-                moveAlso(dx, dy);
-        }
-}
-
-Because move of Point is not overridden by move in PlusPoint, the method moveAlso in Point never calls the method move in PlusPoint.

- -

Thus if you delete the super.move call from PlusPoint and execute the test program:

-
import points.Point;
-import morepoints.PlusPoint;
-class Test {
-    public static void main(String[] args) {
-        PlusPoint pp = new PlusPoint();
-        pp.move(1, 1);
-
-

}

-} -
-it terminates normally. If move of Point were overridden by move in PlusPoint, then this program would recurse infinitely, until a StackoverflowError occurred.

- - -

6.6.6 Example: public Fields, Methods, and Constructors

- -A public class member or constructor is accessible throughout the package where it is declared and from any other package, provided the package in which it is declared is observable (§7.4.3). For example, in the compilation unit:

-

package points;
-public class Point {
-        int x, y;
-        public void move(int dx, int dy) {
-                x += dx; y += dy;
-                moves++;
-        }
-        public static int moves = 0;
-}
-
-the public class Point has as public members the move method and the moves field. These public members are accessible to any other package that has access to package points. The fields x and y are not public and therefore are accessible only from within the package points.

- - -

6.6.7 Example: protected Fields, Methods, and Constructors

- -Consider this example, where the points package declares:

-

package points;
-public class Point {
-        protected int x, y;
-        void warp(threePoint.Point3d a) {
-                if (a.z > 0)         // compile-time error: cannot access a.z
-                        a.delta(this);
-        }
-}
-
-and the threePoint package declares:

-

package threePoint;
-import points.Point;
-public class Point3d extends Point {
-        protected int z;
-        public void delta(Point p) {
-                p.x += this.x;          // compile-time error: cannot access p.x
-                p.y += this.y;          // compile-time error: cannot access p.y
-
-        }
-        public void delta3d(Point3d q) {
-                q.x += this.x;
-                q.y += this.y;
-                q.z += this.z;
-        }
-}
-
-which defines a class Point3d. A compile-time error occurs in the method delta here: it cannot access the protected members x and y of its parameter p, because while Point3d (the class in which the references to fields x and y occur) is a subclass of Point (the class in which x and y are declared), it is not involved in the implementation of a Point (the type of the parameter p). The method delta3d can access the protected members of its parameter q, because the class Point3d is a subclass of Point and is involved in the implementation of a Point3d.

- -

The method delta could try to cast (§5.5, §15.16) its parameter to be a Point3d, but this cast would fail, causing an exception, if the class of p at run time were not Point3d.

- -

A compile-time error also occurs in the method warp: it cannot access the protected member z of its parameter a, because while the class Point (the class in which the reference to field z occurs) is involved in the implementation of a Point3d (the type of the parameter a), it is not a subclass of Point3d (the class in which z is declared).

- - -

6.6.8 Example: private Fields, Methods, and Constructors

- -A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses. In the example:

-

class Point {
-        Point() { setMasterID(); }
-        int x, y;
-        private int ID;
-        private static int masterID = 0;
-        private void setMasterID() { ID = masterID++; }
-}
-
-the private members ID, masterID, and setMasterID may be used only within the body of class Point. They may not be accessed by qualified names, field access expressions, or method invocation expressions outside the body of the declaration of Point.

- -

See §8.8.8 for an example that uses a private constructor.

- - -

6.7 Fully Qualified Names and Canonical Names

- -Every package, top level class, top level interface, and primitive type has a fully qualified name. An array type has a fully qualified name if and only if its element type has a fully qualified name.

-

-Examples:

-

-In the example:

-

package points;
-class Point { int x, y; }
-class PointVec {
-        Point[] vec;
-}
-
-the fully qualified name of the type Point is "points.Point"; the fully qualified name of the type PointVec is "points.PointVec"; and the fully qualified name of the type of the field vec of class PointVec is "points.Point[]".

- -Every package, top level class, top level interface, and primitive type has a canonical name. An array type has a canonical name if and only if its element type has a canonical name. A member class or member interface M declared in another class C has a canonical name if and only if C has a canonical name. In that case, the canonical name of M consists of the canonical name of C, followed by ".", followed by the simple name of M. For every package, top level class, top level interface and primitive type, the canonical name is the same as the fully qualified name. The canonical name of an array type is defined only when the component type of the array has a canonical name. In that case, the canonical name of the array type consists of the canonical name of the component type of the array type followed by "[]".

- -

The difference between a fully qualified name and a canonical name can be seen in examples such as:

-
package p;
-class O1 { class I{}}
-class O2 extends O1{};
-
-
-In this example both p.O1.I and p.O2.I are fully qualified names that denote the same class, but only p.O1.I is its canonical name.

- - -

6.8 Naming Conventions

- -The class libraries of the Java platform attempt to use, whenever possible, names chosen according to the conventions presented here. These conventions help to make code more readable and avoid certain kinds of name conflicts.

- -

We recommend these conventions for use in all programs written in the Java programming language. However, these conventions should not be followed slavishly if long-held conventional usage dictates otherwise. So, for example, the sin and cos methods of the class java.lang.Math have mathematically conventional names, even though these method names flout the convention suggested here because they are short and are not verbs.

- - -

6.8.1 Package Names

- -Names of packages that are to be made widely available should be formed as described in §7.7. Such names are always qualified names whose first identifier consists of two or three lowercase letters that name an Internet domain, such as com, edu, gov, mil, net, org, or a two-letter ISO country code such as uk or jp. Here are examples of hypothetical unique names that might be formed under this convention:

-

com.JavaSoft.jag.Oak
-org.npr.pledge.driver
-uk.ac.city.rugby.game
-
- -

Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved by Sun for naming Java platform packages.

- -

When package names occur in expressions:

- - -

The first component of a package name is normally not easily mistaken for a type name, as a type name normally begins with a single uppercase letter. (The Java programming language does not actually rely on case distinctions to determine whether a name is a package name or a type name.)

- - -

6.8.2 Class and Interface Type Names

- -Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed case with the first letter of each word capitalized. For example:

-

ClassLoader
-SecurityManager
-Thread
-Dictionary
-BufferedInputStream
-
-
- -

Likewise, names of interface types should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces java.io.DataInput and java.io.DataOutput; or it may be an adjective describing a behavior, as for the interfaces Runnable and Cloneable.

- -

Obscuring involving class and interface type names is rare. Names of fields, parameters, and local variables normally do not obscure type names because they conventionally begin with a lowercase letter whereas type names conventionally begin with an uppercase letter.

- - -

6.8.3 Type Variable Names

- -Type variable names should be pithy (single character if possible) yet evocative, and should not include lower case letters.

- -


-

- Discussion -

- - This makes it easy to distinguish formal type parameters from ordinary classes and interfaces.

-


- -

- -Container types should use the name E for their element type. Maps should use K for the type of their keys and V for the type of their values. The name X should be used for arbitrary exception types. We use T for type, whenever there isn't anything more specific about the type to distinguish it.

- -


-

- Discussion -

- - This is often the case in generic methods.

-


- -

- -If there are multiple type parameters that denote arbitrary types, one should use letters that neighbor T in the alphabet, such as S. Alternately, it is acceptable to use numeric subscripts (e.g., T1, T2) to distinguish among the different type variables. In such cases, all the variables with the same prefix should be subscripted.

- -


-

- Discussion -

- - If a generic method appears inside a generic class, it's a good idea to avoid using the same names for the type parameters of the method and class, to avoid confusion. The same applies to nested generic classes.

-


- -

-


- -

- Discussion -

-

- - These conventions are illustrated in the code snippets below:

-

public class HashSet<E> extends AbstractSet<E> { ... }
-public class HashMap<K,V> extends AbstractMap<K,V> { ... }
-public class ThreadLocal<T> { ... }
-public interface Functor<T, X extends Throwable> {
-    T eval() throws X;
-}
-
- -

-


- -When type parameters do not fall conveniently into one of the categories mentioned, names should be chosen to be as meaningful as possible within the confines of a single letter. The names mentioned above (E, K, T, V, X) should not be used for type parameters that do not fall into the designated categories.

- - -

6.8.4 Method Names

- -Method names should be verbs or verb phrases, in mixed case, with the first letter lowercase and the first letter of any subsequent words capitalized. Here are some additional specific conventions for method names:

-

-Whenever possible and appropriate, basing the names of methods in a new class on names in an existing class that is similar, especially a class from the Java Application Programming Interface classes, will make it easier to use.

- -

Method names cannot obscure or be obscured by other names (§6.5.7).

- - -

6.8.5 Field Names

- -Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. Note that well-designed classes have very few public or protected fields, except for fields that are constants (final static fields) (§6.8.6).

- -

Fields should have names that are nouns, noun phrases, or abbreviations for nouns. Examples of this convention are the fields buf, pos, and count of the class java.io.ByteArrayInputStream and the field bytesTransferred of the class java.io.InterruptedIOException.

- -

Obscuring involving field names is rare.

- - -

6.8.6 Constant Names

- -The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class Character.

- -

A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:

-
interface ProcessStates {
-        int PS_RUNNING = 0;
-        int PS_SUSPENDED = 1;
-}
-
-Obscuring involving constant names is rare:

-

- -

6.8.7 Local Variable and Parameter Names

- -Local variable and parameter names should be short, yet meaningful. They are often short sequences of lowercase letters that are not words. For example:

-

- -

One-character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type. Conventional one-character names are:

- - -

Local variable or parameter names that consist of only two or three lowercase letters should not conflict with the initial country codes and domain names that are the first component of unique package names (§7.7).

- - -

- - -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - Packages - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 7

- -

Packages

-

- -Programs are organized as sets of packages. Each package has its own set of names for types, which helps to prevent name conflicts. A top level type is accessible (§6.6) outside the package that declares it only if the type is declared public.

- -The naming structure for packages is hierarchical (§7.1). The members of a package are class and interface types (§7.6), which are declared in compilation units of the package, and subpackages, which may contain compilation units and subpackages of their own.

- -A package can be stored in a file system (§7.2.1) or in a database (§7.2.2). Packages that are stored in a file system may have certain constraints on the organization of their compilation units to allow a simple implementation to find classes easily.

- -A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.

- -

For small programs and casual development, a package can be unnamed (§7.4.2) or have a simple name, but if code is to be widely distributed, unique package names should be chosen (§7.7). This can prevent the conflicts that would otherwise occur if two development groups happened to pick the same package name and these packages were later to be used in a single program.

- - -

7.1 Package Members

- -The members of a package are its subpackages and all the top level (§7.6) class types (§8) and top level interface types (§9) declared in all the compilation units (§7.3) of the package.

- -For example, in the Java Application Programming Interface:

-

-If the fully qualified name (§6.7) of a package is P, and Q is a subpackage of P, then P.Q is the fully qualified name of the subpackage.

- -A package may not contain two members of the same name, or a compile-time error results.

- -

Here are some examples:

- - -

The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in itself other than the prohibition against a package having a subpackage with the same simple name as a top level type (§7.6) declared in that package. There is no special access relationship between a package named oliver and another package named oliver.twist, or between packages named evelyn.wood and evelyn.waugh. For example, the code in a package named oliver.twist has no better access to the types declared within package oliver than code in any other package.

- - -

7.2 Host Support for Packages

- -Each host determines how packages, compilation units, and subpackages are created and stored, and which compilation units are observable (§7.3) in a particular compilation.

- -

The observability of compilation units in turn determines which packages are observable, and which packages are in scope.

- -

The packages may be stored in a local file system in simple implementations of the Java platform. Other implementations may use a distributed file system or some form of database to store source and/or binary code.

- - -

7.2.1 Storing Packages in a File System

- -As an extremely simple example, all the packages and source and binary code on a system might be stored in a single directory and its subdirectories. Each immediate subdirectory of this directory would represent a top level package, that is, one whose fully qualified name consists of a single simple name. The directory might contain the following immediate subdirectories:

-

com
-gls
-jag
-java
-wnj
-
-where directory java would contain the Java Application Programming Interface packages; the directories jag, gls, and wnj might contain packages that three of the authors of this specification created for their personal use and to share with each other within this small group; and the directory com would contain packages procured from companies that used the conventions described in §7.7 to generate unique names for their packages.

- -

Continuing the example, the directory java would contain, among others, the following subdirectories:

-
applet 
-awt
-io
-lang
-net
-util
-
-corresponding to the packages java.applet, java.awt, java.io, java.lang, java.net, and java.util that are defined as part of the Java Application Programming Interface.

- -

Still continuing the example, if we were to look inside the directory util, we might see the following files:

-
-BitSet.java                             Observable.java
-BitSet.class                            Observable.class
-Date.java                               Observer.java
-Date.class                              Observer.class
-...
-
-where each of the .java files contains the source for a compilation unit (§7.3) that contains the definition of a class or interface whose binary compiled form is contained in the corresponding .class file.

- -

Under this simple organization of packages, an implementation of the Java platform would transform a package name into a pathname by concatenating the components of the package name, placing a file name separator (directory indicator) between adjacent components.

- -

For example, if this simple organization were used on a UNIX system, where the file name separator is /, the package name:

-
jag.scrabble.board
-
-would be transformed into the directory name:

-

jag/scrabble/board
-
-and:

-

com.sun.sunsoft.DOE
-
-would be transformed to the directory name:

-

com/sun/sunsoft/DOE
-
-

A package name component or class name might contain a character that cannot correctly appear in a host file system's ordinary directory name, such as a Unicode character on a system that allows only ASCII characters in file names. As a convention, the character can be escaped by using, say, the @ character followed by four hexadecimal digits giving the numeric value of the character, as in the \uxxxx escape (§3.3), so that the package name:

-
-children.activities.crafts.papierM\u00e2ch\u00e9
-
-which can also be written using full Unicode as:

-

children.activities.crafts.papierMâché
-
-might be mapped to the directory name:

-

children/activities/crafts/papierM@00e2ch@00e9
-
-If the @ character is not a valid character in a file name for some given host file system, then some other character that is not valid in a identifier could be used instead.

- - -

7.2.2 Storing Packages in a Database

- -A host system may store packages and their compilation units and subpackages in a database.

- -

Such a database must not impose the optional restrictions (§7.6) on compilation units in file-based implementations. For example, a system that uses a database to store packages may not enforce a maximum of one public class or interface per compilation unit.

- -Systems that use a database must, however, provide an option to convert a program to a form that obeys the restrictions, for purposes of export to file-based implementations.

- - -

7.3 Compilation Units

- -CompilationUnit is the goal symbol (§2.1) for the syntactic grammar (§2.3) of Java programs. It is defined by the following productions:

-

-CompilationUnit:
-        PackageDeclarationopt ImportDeclarationsopt TypeDeclarationsopt
-ImportDeclarations:
-        ImportDeclaration
-        ImportDeclarations ImportDeclaration
-
-TypeDeclarations:
-        TypeDeclaration
-        TypeDeclarations TypeDeclaration
-        
-
-Types declared in different compilation units can depend on each other, circularly. A Java compiler must arrange to compile all such types at the same time.

- -A compilation unit consists of three parts, each of which is optional:

-

-Which compilation units are observable is determined by the host system. However, all the compilation units of the package java and its subpackages lang and io must always be observable. The observability of a compilation unit influences the observability of its package (§7.4.3).

- -Every compilation unit automatically and implicitly imports every public type name declared by the predefined package java.lang, so that the names of all those types are available as simple names, as described in §7.5.5.

- - -

7.4 Package Declarations

- -A package declaration appears within a compilation unit to indicate the package to which the compilation unit belongs.

- - -

7.4.1 Named Packages

- -A package declaration in a compilation unit specifies the name (§6.2) of the package to which the compilation unit belongs.

-

-PackageDeclaration:
-        Annotationsopt package PackageName ;
-
-The keyword package may optionally be preceded by annotation modifiers (§9.7). If an annotation a on a package declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.PACKAGE, or a compile-time error occurs.

- -The package name mentioned in a package declaration must be the fully qualified name (§6.7) of the package.

- - -

7.4.1.1 Package Annotations

- -Annotations may be used on package declarations, with the restriction that at most one annotated package declaration is permitted for a given package.

-


- -

- Discussion -

- - The manner in which this restriction is enforced must, of necessity, vary from implementation to implementation. The following scheme is strongly recommended for file-system-based implementations: The sole annotated package declaration, if it exists, is placed in a source file called package-info.java in the directory containing the source files for the package. This file does not contain the source for a class called package-info.java; indeed it would be illegal for it to do so, as package-info is not a legal identifier. Typically package-info.java contains only a package declaration, preceded immediately by the annotations on the package. While the file could technically contain the source code for one or more package-private classes, it would be very bad form.

- -It is recommended that package-info.java, if it is present, take the place of package.html for javadoc and other similar documentation generation systems. If this file is present, the documentation generation tool should look for the package documentation comment immediately preceding the (possibly annotated) package declaration in package-info.java. In this way, package-info.java becomes the sole repository for package level annotations and documentation. If, in future, it becomes desirable to add any other package-level information, this file should prove a convenient home for this information.

-


- -

- -

- - -

7.4.2 Unnamed Packages

- -A compilation unit that has no package declaration is part of an unnamed package.

- -

Note that an unnamed package cannot have subpackages, since the syntax of a package declaration always includes a reference to a named top level package.

- -As an example, the compilation unit:

-

class FirstCall {
-        public static void main(String[] args) {
-                System.out.println("Mr. Watson, come here. "
-                                        + "I want you.");
-        }
-}
-
-defines a very simple compilation unit as part of an unnamed package.

- -An implementation of the Java platform must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.

- -

In implementations of the Java platform that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is observable at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.

- -

Unnamed packages are provided by the Java platform principally for convenience when developing small or temporary applications or when just beginning development.

- - -

7.4.3 Observability of a Package

- -A package is observable if and only if either:

-

-

One can conclude from the rule above and from the requirements on observable compilation units, that the packages java, java.lang, and java.io are always observable.

- - -

7.4.4 Scope of a Package Declaration

- -The scope of the declaration of an observable (§7.4.3) top level package is all observable compilation units (§7.3). The declaration of a package that is not observable is never in scope. Subpackage declarations are never in scope.

- -

It follows that the package java is always in scope (§6.3).

- -Package declarations never shadow other declarations.

- - -

7.5 Import Declarations

- -An import declaration allows a static member or a named type to be referred to by a simple name (§6.2) that consists of a single identifier. Without the use of an appropriate import declaration, the only way to refer to a type declared in another package, or a static member of another type, is to use a fully qualified name (§6.7).

-

-ImportDeclaration:
-        SingleTypeImportDeclaration
-        TypeImportOnDemandDeclaration   
-        SingleStaticImportDeclaration   
-        StaticImportOnDemandDeclaration
-        
-
-A single-type-import declaration (§7.5.1) imports a single named type, by mentioning its canonical name (§6.7).

- -A type-import-on-demand declaration (§7.5.2) imports all the accessible (§6.6) types of a named type or package as needed. It is a compile time error to import a type from the unnamed package.

- -A single static import declaration (§7.5.3) imports all accessible static members with a given name from a type, by giving its canonical name.

- -A static-import-on-demand declaration (§7.5.4) imports all accessible static members of a named type as needed.

- -The scope of a type imported by a single-type-import declaration (§7.5.1) or a type-import-on-demand declaration (§7.5.2) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.

- -The scope of a member imported by a single-static-import declaration (§7.5.3) or a static-import-on-demand declaration (§7.5.4) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.

- -An import declaration makes types available by their simple names only within the compilation unit that actually contains the import declaration. The scope of the entities(s) it introduces specifically does not include the package statement, other import declarations in the current compilation unit, or other compilation units in the same package. See §7.5.6 for an illustrative example.

- - -

7.5.1 Single-Type-Import Declaration

- -A single-type-import declaration imports a single type by giving its canonical name, making it available under a simple name in the class and interface declarations of the compilation unit in which the single-type import declaration appears.

-

-SingleTypeImportDeclaration:
-   import TypeName ;
-
-The TypeName must be the canonical name of a class or interface type; a compile-time error occurs if the named type does not exist. The named type must be accessible (§6.6) or a compile-time error occurs.

- -A single-type-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

-

-throughout c.

- -

The example:

-
import java.util.Vector;
-
-causes the simple name Vector to be available within the class and interface declarations in a compilation unit. Thus, the simple name Vector refers to the type declaration Vector in the package java.util in all places where it is not shadowed (§6.3.1) or obscured (§6.3.2) by a declaration of a field, parameter, local variable, or nested type declaration with the same name.

- -


-

- Discussion -

- - Note that Vector is declared as a generic type. Once imported, the name Vector can be used without qualification in a parameterized type such as Vector<String>, or as the raw type Vector.

- -This highlights a limitation of the import declaration. A type nested inside a generic type declaration can be imported, but its outer type is always erased.

-


- -

- -If two single-type-import declarations in the same compilation unit attempt to import types with the same simple name, then a compile-time error occurs, unless the two types are the same type, in which case the duplicate declaration is ignored. If the type imported by the the single-type-import declaration is declared in the compilation unit that contains the import declaration, the import declaration is ignored. If a compilation unit contains both a single-static-import (§7.5.3) declaration that imports a type whose simple name is n, and a single-type-import declaration (§7.5.1) that imports a type whose simple name is n, a compile-time error occurs.

- -If another top level type with the same simple name is otherwise declared in the current compilation unit except by a type-import-on-demand declaration (§7.5.2) or a static-import-on-demand declaration (§7.5.4), then a compile-time error occurs.

- -So the sample program:

-

import java.util.Vector;
-class Vector { Object[] vec; }
-
-causes a compile-time error because of the duplicate declaration of Vector, as does:

-

import java.util.Vector;
-import myVector.Vector;
-
-where myVector is a package containing the compilation unit:

-

package myVector;
-public class Vector { Object[] vec; }
-
-The compiler keeps track of types by their binary names (§13.1).

- -

Note that an import statement cannot import a subpackage, only a type. For example, it does not work to try to import java.util and then use the name util.Random to refer to the type java.util.Random:

-
import java.util;              // incorrect: compile-time error
-class Test { util.Random generator; }
-
- -

7.5.2 Type-Import-on-Demand Declaration

- -A type-import-on-demand declaration allows all accessible (§6.6) types declared in the type or package named by a canonical name to be imported as needed.

-

-TypeImportOnDemandDeclaration:
-        import PackageOrTypeName . * ;
-
-It is a compile-time error for a type-import-on-demand declaration to name a type or package that is not accessible. Two or more type-import-on-demand declarations in the same compilation unit may name the same type or package. All but one of these declarations are considered redundant; the effect is as if that type was imported only once.

- -If a compilation unit contains both a static-import-on-demand declaration and a type-import-on-demand (§7.5.2) declaration that name the same type, the effect is as if the static member types of that type were imported only once.

- -

- -It is not a compile-time error to name the current package or java.lang in a type-import-on-demand declaration. The type-import-on-demand declaration is ignored in such cases.

- -A type-import-on-demand declaration never causes any other declaration to be shadowed.

- -The example:

-

import java.util.*;
-
-causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places in the compilation unit where that type declaration is not shadowed (§6.3.1) or obscured (§6.3.2). The declaration might be shadowed by a single-type-import declaration of a type whose simple name is Vector; by a type named Vector and declared in the package to which the compilation unit belongs; or any nested classes or interfaces. The declaration might be obscured by a declaration of a field, parameter, or local variable named Vector (It would be unusual for any of these conditions to occur.)

- - -

7.5.3 Single Static Import Declaration

- -A single-static-import declaration imports all accessible (§6.6) static members with a given simple name from a type. This makes these static members available under their simple name in the class and interface declarations of the compilation unit in which the single-static import declaration appears.

-

-SingleStaticImportDeclaration:
-        import static TypeName . Identifier;
-
-The TypeName must be the canonical name of a class or interface type; a compile-time error occurs if the named type does not exist. The named type must be accessible (§6.6) or a compile-time error occurs. The Identifier must name at least one static member of the named type; a compile-time error occurs if there is no member of that name or if all of the named members are not accessible.

- -A single-static-import declaration d in a compilation unit c of package p that imports a field named n shadows the declaration of any static field named n imported by a static-import-on-demand declaration in c, throughout c.

- -A single-static-import declaration d in a compilation unit c of package p that imports a method named n with signature s shadows the declaration of any static method named n with signature s imported by a static-import-on-demand declaration in c, throughout c.

- -A single-static-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

-

-throughout c.

- -Note that it is permissable for one single-static-import declaration to import several fields or types with the same name, or several methods with the same name and signature.

- -If a compilation unit contains both a single-static-import (§7.5.3) declaration that imports a type whose simple name is n, and a single-type-import declaration (§7.5.1) that imports a type whose simple name is n, a compile-time error occurs.

- -If a single-static-import declaration imports a type whose simple name is n, and the compilation unit also declares a top level type (§7.6) whose simple name is n, a compile-time error occurs.

- - -

7.5.4 Static-Import-on-Demand Declaration

- -A static-import-on-demand declaration allows all accessible (§6.6) static members declared in the type named by a canonical name to be imported as needed.

-

-StaticImportOnDemandDeclaration:
-         import static TypeName . * ;
-
-It is a compile-time error for a static-import-on-demand declaration to name a type that does not exist or a type that is not accessible. Two or more static-import-on-demand declarations in the same compilation unit may name the same type or package; the effect is as if there was exactly one such declaration. Two or more static-import-on-demand declarations in the same compilation unit may name the same member; the effect is as if the member was imported exactly once.

- -Note that it is permissable for one static-import-on-demand declaration to import several fields or types with the same name, or several methods with the same name and signature.

- -If a compilation unit contains both a static-import-on-demand declaration and a type-import-on-demand (§7.5.2) declaration that name the same type, the effect is as if the static member types of that type were imported only once.

- -

- -A static-import-on-demand declaration never causes any other declaration to be shadowed.

- -

- -

- - -

7.5.5 Automatic Imports

- -Each compilation unit automatically imports all of the public type names declared in the predefined package java.lang, as if the declaration:

-

import java.lang.*;
-
-appeared at the beginning of each compilation unit, immediately following any package statement.

- -

- - -

7.5.6 A Strange Example

- -Package names and type names are usually different under the naming conventions described in §6.8. Nevertheless, in a contrived example where there is an unconventionally-named package Vector, which declares a public class whose

- -

- -name is Mosquito:

-

package Vector;
-public class Mosquito { int capacity; }
-
-and then the compilation unit:

-

package strange.example;
-import java.util.Vector;
-import Vector.Mosquito;
-class Test {
-        public static void main(String[] args) {
-                System.out.println(new Vector().getClass());
-                System.out.println(new Mosquito().getClass());
-        }
-}
-
-the single-type-import declaration (§7.5.1) importing class Vector from package java.util does not prevent the package name Vector from appearing and being correctly recognized in subsequent import declarations. The example compiles and produces the output:

-

class java.util.Vector
-class Vector.Mosquito
-
- -

7.6 Top Level Type Declarations

- -A top level type declaration declares a top level class type (§8) or a top level interface type (§9):

-

-TypeDeclaration:
-        ClassDeclaration
-        InterfaceDeclaration
-        ;
-
-By default, the top level types declared in a package are accessible only within the compilation units of that package, but a type may be declared to be public to grant access to the type from code in other packages (§6.6, §8.1.1, §9.1.1).

- -The scope of a top level type is all type declarations in the package in which the top level type is declared.

- -If a top level type named T is declared in a compilation unit of a package whose fully qualified name is P, then the fully qualified name of the type is P.T. If the type is declared in an unnamed package (§7.4.2), then the type has the fully qualified name T.

- -

- -

- -Thus in the example:

-

package wnj.points;
-class Point { int x, y; }
-
-the fully qualified name of class Point is wnj.points.Point.

- -An implementation of the Java platform must keep track of types within packages by their binary names (§13.1). Multiple ways of naming a type must be expanded to binary names to make sure that such names are understood as referring to the same type.

- -

For example, if a compilation unit contains the single-type-import declaration (§7.5.1):

- -

-
import java.util.Vector;
-
-

- -then within that compilation unit the simple name Vector and the fully qualified name java.util.Vector refer to the same type.

- -When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

-

-

- -This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

- -

When packages are stored in a database (§7.2.2), the host system must not impose such restrictions. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.

- -A compile-time error occurs if the name of a top level type appears as the name of any other top level class or interface type declared in the same package (§7.6).

- -A compile-time error occurs if the name of a top level type is also declared as a type by a single-type-import declaration (§7.5.1) in the compilation unit (§7.3) containing the type declaration.

- -

- -

- -

In the example:

-
class Point { int x, y; }
-
-the class Point is declared in a compilation unit with no package statement, and thus Point is its fully qualified name, whereas in the example:

-

package vista;
-class Point { int x, y; }
-
-the fully qualified name of the class Point is vista.Point. (The package name vista is suitable for local or personal use; if the package were intended to be widely distributed, it would be better to give it a unique package name (§7.7).)

- -

In the example:

-
package test;
-import java.util.Vector;
-class Point {
-
   int x, y;
-
}
-interface Point {                                                                                       // compile-time error #1
-        int getR();
-        int getTheta();
-}
-class Vector { Point[] pts; }                                                                                   // compile-time error #2
-
-

- -the first compile-time error is caused by the duplicate declaration of the name Point as both a class and an interface in the same package. A second error detected at compile time is the attempt to declare the name Vector both by a class type declaration and by a single-type-import declaration.

- -

Note, however, that it is not an error for the name of a class to also to name a type that otherwise might be imported by a type-import-on-demand declaration (§7.5.2) in the compilation unit (§7.3) containing the class declaration. In the example:

- -

-
package test;
-import java.util.*;
-class Vector { Point[] pts; }                                                                                   // not a compile-time error
-
-the declaration of the class Vector is permitted even though there is also a class java.util.Vector. Within this compilation unit, the simple name Vector refers to the class test.Vector, not to java.util.Vector (which can still be referred to by code within the compilation unit, but only by its fully qualified name).

- - -

- -

As another example, the compilation unit:

-
package points;
-class Point {
-        int x, y;               // coordinates
-        PointColor color;       // color of this point
-        Point next;             // next point with this color
-        static int nPoints;
-}
-class PointColor {
-        Point first;            // first point with this color
-        PointColor(int color) {
-                this.color = color;
-        }
-        private int color;      // color components
-}
-
-defines two classes that use each other in the declarations of their class members. Because the class types Point and PointColor have all the type declarations in package points, including all those in the current compilation unit, as their scope, this example compiles correctly-that is, forward reference is not a problem.

- -It is a compile-time error if a top level type declaration contains any one of the following access modifiers: protected, private or static.

- -

- - -

7.7 Unique Package Names

- -Developers should take steps to avoid the possibility of two published packages having the same name by choosing unique package names for packages that are widely distributed. This allows packages to be easily and automatically installed and catalogued. This section specifies a suggested convention for generating such unique package names. Implementations of the Java platform are encouraged to provide automatic support for converting a set of packages from local and casual package names to the unique name format described here.

- -

If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create a situation that is difficult or impossible for the user or programmer to resolve. The class ClassLoader can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a naïve program.

- -

You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as sun.com. You then reverse this name, component by component, to obtain, in this example, com.sun, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names.

- -

In some cases, the internet domain name may not be a valid package name. Here are some suggested conventions for dealing with these situations:

- -

Such a convention might specify that certain directory name components be division, department, project, machine, or login names. Some possible examples:

-
com.sun.sunsoft.DOE
-com.sun.java.jag.scrabble
-com.apple.quicktime.v2
-edu.cmu.cs.bovik.cheese
-gov.whitehouse.socks.mousefinder
-
-The first component of a unique package name is always written in all-lowercase ASCII letters and should be one of the top level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. For more information, refer to the documents stored at ftp://rs.internic.net/rfc, for example, rfc920.txt and rfc1032.txt.

- -

The name of a package is not meant to imply where the package is stored within the Internet; for example, a package named edu.cmu.cs.bovik.cheese is not necessarily obtainable from Internet address cmu.edu or from cs.cmu.edu or from bovik.cs.cmu.edu. The suggested convention for generating unique package names is merely a way to piggyback a package naming convention on top of an existing, widely known unique name registry instead of having to create a separate registry for package names.

- -

- - -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - - Classes - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 8

- -

Classes

-

- -Class declarations define new reference types and describe how they are implemented (§8.1).

- -A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.

- -This chapter discusses the common semantics of all classes-top level (§7.6) and nested (including member classes (§8.5, §9.5), local classes (§14.3) and anonymous classes (§15.9.5)). Details that are specific to particular kinds of classes are discussed in the sections dedicated to these constructs.

- -A named class may be declared abstract (§8.1.1.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. A class may be declared final (§8.1.1.2), in which case it cannot have subclasses. If a class is declared public, then it can be referred to from other packages. Each class except Object is an extension of (that is, a subclass of) a single existing class (§8.1.4) and may implement interfaces (§8.1.5). Classes may be generic, that is, they may declare type variables (§4.4) whose bindings may differ among different instances of the class.

- -Classes may be decorated with annotations (§9.7) just like any other kind of declaration.

- -The body of a class declares members (fields and methods and nested classes and interfaces), instance and static initializers, and constructors (§8.1.6). The scope (§6.3) of a member (§8.2) is the entire body of the declaration of the class to which the member belongs. Field, method, member class, member interface, and constructor declarations may include the access modifiers (§6.6) public, protected, or private. The members of a class include both declared and inherited members (§8.2). Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared class members and interface members can hide class or interface members declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.

- -Field declarations (§8.3) describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared final (§8.3.1.2), in which case it can be assigned to only once. Any field declaration may include an initializer.

- -Member class declarations (§8.5) describe nested classes that are members of the surrounding class. Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (§8.1.3).

- -Member interface declarations (§8.5) describe nested interfaces that are members of the surrounding class.

- -Method declarations (§8.4) describe code that may be invoked by method invocation expressions (§15.12). A class method is invoked relative to the class type; an instance method is invoked with respect to some particular object that is an instance of a class type. A method whose declaration does not indicate how it is implemented must be declared abstract. A method may be declared final (§8.4.3.3), in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent native code (§8.4.3.4). A synchronized method (§8.4.3.6) automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a synchronized statement (§14.19), thus allowing its activities to be synchronized with those of other threads (§17).

- -Method names may be overloaded (§8.4.9).

- -Instance initializers (§8.6) are blocks of executable code that may be used to help initialize an instance when it is created (§15.9).

- -Static initializers (§8.7) are blocks of executable code that may be used to help initialize a class.

- -Constructors (§8.8) are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded (§8.8.8).

- - -

8.1 Class Declaration

- -A class declaration specifies a new named reference type. There are two kinds of class declarations - normal class declarations and enum declarations:

- -

-ClassDeclaration:
-		NormalClassDeclaration	
-		EnumDeclaration
-
-NormalClassDeclaration:
-	ClassModifiersopt class Identifier TypeParametersopt Superopt Interfacesopt 
-ClassBody
-
-
-The rules in this section apply to all class declarations unless this specification explicitly states otherwise. In many cases, special restrictions apply to enum declarations. Enum declarations are described in detail in §8.9.

- -The Identifier in a class declaration specifies the name of the class. A compile-time error occurs if a class has the same simple name as any of its enclosing classes or interfaces.

- - -

8.1.1 Class Modifiers

- -A class declaration may include class modifiers.

-

-ClassModifiers:
-	ClassModifier
-	ClassModifiers ClassModifier
-
-ClassModifier: one of
-	Annotation public protected private
-	abstract static final strictfp 
-
-Not all modifiers are applicable to all kinds of class declarations. The access modifier public pertains only to top level classes (§7.6) and to member classes (§8.5, §9.5), and is discussed in §6.6, §8.5 and §9.5. The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration (§8.5) and are discussed in §8.5.1. The access modifier static pertains only to member classes (§8.5, §9.5). A compile-time error occurs if the same modifier appears more than once in a class declaration.

- -If an annotation a on a class declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.TYPE, or a compile-time error occurs. Annotation modifiers are described further in §9.7.

- -

If two or more class modifiers appear in a class declaration, then it is customary, though not required, that they appear in the order consistent with that shown above in the production for ClassModifier.

- - -

8.1.1.1 abstract Classes

- -An abstract class is a class that is incomplete, or to be considered incomplete. Normal classes may have abstract methods (§8.4.3.1, §9.4), that is methods that are declared but not yet implemented, only if they are abstract classes. If a normal class that is not abstract contains an abstract method, then a compile-time error occurs.

- -Enum types (§8.9) must not be declared abstract; doing so will result in a compile-time error. It is a compile-time error for an enum type E to have an abstract method m as a member unless E has one or more enum constants, and all of E's enum constants have class bodies that provide concrete implementations of m. It is a compile-time error for the class body of an enum constant to declare an abstract method.

- -

- -A class C has abstract methods if any of the following is true:

-

-

In the example:

- -
abstract class Point {
-	int x = 1, y = 1;
-	void move(int dx, int dy) {
-		x += dx;
-		y += dy;
-		alert();
-	}
-	abstract void alert();
-}
-abstract class ColoredPoint extends Point {
-	int color;
-}
-
-class SimplePoint extends Point {
-	void alert() { }
-}
-
-a class Point is declared that must be declared abstract, because it contains a declaration of an abstract method named alert. The subclass of Point named ColoredPoint inherits the abstract method alert, so it must also be declared abstract. On the other hand, the subclass of Point named SimplePoint provides an implementation of alert, so it need not be abstract.

- -A compile-time error occurs if an attempt is made to create an instance of an abstract class using a class instance creation expression (§15.9).

- -

Thus, continuing the example just shown, the statement:

-
	Point p = new Point();
-
-would result in a compile-time error; the class Point cannot be instantiated because it is abstract. However, a Point variable could correctly be initialized with a reference to any subclass of Point, and the class SimplePoint is not abstract, so the statement:

-

	Point p = new SimplePoint();
-
-would be correct.

- -

A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class. Thus, in the example just given, instantiation of a SimplePoint causes the default constructor and field initializers for x and y of Point to be executed.

- -It is a compile-time error to declare an abstract class type such that it is not possible to create a subclass that implements all of its abstract methods. This situation can occur if the class would have as members two abstract methods that have the same method signature (§8.4.2) but incompatible return types.

- -

As an example, the declarations:

-
interface Colorable { void setColor(int color); }
-abstract class Colored implements Colorable {
-	abstract int setColor(int color);
-}
-
-result in a compile-time error: it would be impossible for any subclass of class Colored to provide an implementation of a method named setColor, taking one argument of type int, that can satisfy both abstract method specifications, because the one in interface Colorable requires the same method to return no value, while the one in class Colored requires the same method to return a value of type int (§8.4).

- -

A class type should be declared abstract only if the intent is that subclasses can be created to complete the implementation. If the intent is simply to prevent instantiation of a class, the proper way to express this is to declare a constructor (§8.8.10) of no arguments, make it private, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables. The class Math is an example of a class that cannot be instantiated; its declaration looks like this:

-
public final class Math {
-	private Math() { }		// never instantiate this class
-	. . . declarations of class variables and methods . . .
-
-

}

-
- -

8.1.1.2 final Classes

- -A class can be declared final if its definition is complete and no subclasses are desired or required. A compile-time error occurs if the name of a final class appears in the extends clause (§8.1.4) of another class declaration; this implies that a final class cannot have any subclasses. A compile-time error occurs if a class is declared both final and abstract, because the implementation of such a class could never be completed (§8.1.1.1).

- -

Because a final class never has any subclasses, the methods of a final class are never overridden (§8.4.8.1).

- - -

8.1.1.3 strictfp Classes

- -The effect of the strictfp modifier is to make all float or double expressions within the class declaration be explicitly FP-strict (§15.4). This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp.

- -

Note also that all float or double expressions within all variable initializers, instance initializers, static initializers and constructors of the class will also be explicitly FP-strict.

- - -

8.1.2 Generic Classes and Type Parameters

- -A class is generic if it declares one or more type variables (§4.4). These type variables are known as the type parameters of the class. The type parameter section follows the class name and is delimited by angle brackets. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.

- -


-

- Discussion -

- - For instance, executing the code

-

Vector<String> x = new Vector<String>(); 
-Vector<Integer> y = new Vector<Integer>(); 
-boolean b = x.getClass() == y.getClass();
-
-will result in the variable b holding the value true.

-


- -

-

-TypeParameters ::= < TypeParameterList >
-
-TypeParameterList    ::= TypeParameterList , TypeParameter
-
-                      |  TypeParameter
-
-It is a compile-time error if a generic class is a direct or indirect subclass of Throwable.

- -


-

- Discussion -

- - This restriction is needed since the catch mechanism of the Java virtual machine works only with non-generic classes.

- -

- -The scope of a class' type parameter is the entire declaration of the class including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

- -It is a compile-time error to refer to a type parameter of a class C anywhere in the declaration of a static member of C or the declaration of a static member of any type declaration nested within C. It is a compile-time error to refer to a type parameter of a class C within a static initializer of C or any class nested within C.

- -


-

- Discussion -

- - Example: Mutually recursive type variable bounds.

-

interface ConvertibleTo<T> { 
-   T convert(); 
-} 
-class ReprChange<T implements ConvertibleTo<S>, 
-                 S implements ConvertibleTo<T>> { 
-   T t; 
-   void set(S s) { t = s.convert(); } 
-   S get() { return t.convert(); } 
-}
-
-
-

-Parameterized class declarations can be nested inside other declarations.

-


- -

- Discussion -

- - This is illustrated in the following example:

-

class Seq<T> { 
-   T head; 
-   Seq<T> tail; 
-   Seq() { this(null, null); } 
-   boolean isEmpty() { return tail == null; }
-   Seq(T head, Seq<T> tail) { this.head = head; this.tail = tail; }
-   class Zipper<S> { 
-		Seq<Pair<T,S>> zip(Seq<S> that) { 
-     			if (this.isEmpty() || that.isEmpty())
-				return new Seq<Pair<T,S>>(); 
-     			else 
-				return new Seq<Pair<T,S>>( 
-					new Pair<T,S>(this.head, that.head), 
-					this.tail.zip(that.tail));
-		}
-   }
-}
-class Pair<T, S> {
-	T fst; S Snd;
-	Pair(T f, S s) {fst = f; snd = s;}
-}
-
-class Client {
-	{
-		Seq<String> strs = 
-		new Seq<String>("a", new Seq<String>("b", 
-					new Seq<String>()));
-   		Seq<Number> nums = 
-			new Seq<Number>(new Integer(1), 
-					 new Seq<Number>(new Double(1.5), 
-													new Seq<Number>()));
-		Seq<String>.Zipper<Number> zipper = 
-					strs.new Zipper<Number>();
-		Seq<Pair<String,Number>> combined = zipper.zip(nums);
-	}
-}
-
-
-
- -

8.1.3 Inner Classes and Enclosing Instances

- -An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

- -

To illustrate these rules, consider the example below:

-
class HasStatic{
-	static int j = 100;
-}
-class Outer{
-	class Inner extends HasStatic{
-		static final int x = 3;			// ok - compile-time constant
-		static int y = 4; 			// compile-time error, an inner class
-	}
-	static class NestedButNotInner{
-		static int z = 5; 			// ok, not an inner class
-	}
-	interface NeverInner{}				// interfaces are never inner
-}
-
-Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Member interfaces (§8.5) are always implicitly static so they are never considered to be inner classes.

- -A statement or expression occurs in a static context if and only if the innermost method, constructor, instance initializer, static initializer, field initializer, or explicit constructor invocation statement enclosing the statement or expression is a static method, a static initializer, the variable initializer of a static variable, or an explicit constructor invocation statement (§8.8.7).

- -An inner class C is a direct inner class of a class O if O is the immediately lexically enclosing class of C and the declaration of C does not occur in a static context. A class C is an inner class of class O if it is either a direct inner class of O or an inner class of an inner class of O.

- -A class O is the zeroth lexically enclosing class of itself. A class O is the nth lexically enclosing class of a class C if it is the immediately enclosing class of the n-1st lexically enclosing class of C.

- -An instance i of a direct inner class C of a class O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (§15.9.2).

- -An object o is the zeroth lexically enclosing instance of itself. An object o is the nth lexically enclosing instance of an instance i if it is the immediately enclosing instance of the n-1st lexically enclosing instance of i. -

- When an inner class refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used. A blank final (§4.12.4) field of a lexically enclosing class may not be assigned within an inner class.

- -An instance of an inner class I whose declaration occurs in a static context has no lexically enclosing instances. However, if I is immediately declared within a static method or static initializer then I does have an enclosing block, which is the innermost block statement lexically enclosing the declaration of I.

- -Furthermore, for every superclass S of C which is itself a direct inner class of a class SO, there is an instance of SO associated with i, known as the immediately enclosing instance of i with respect to S. The immediately enclosing instance of an object with respect to its class' direct superclass, if any, is determined when the superclass constructor is invoked via an explicit constructor invocation statement.

- -Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned (§16) before the body of the inner class.

- -

Inner classes include local (§14.3), anonymous (§15.9.5) and non-static member classes (§8.5). Here are some examples:

-
class Outer {
-	int i = 100;
-	static void classMethod() {
-		final int l = 200;
-		class LocalInStaticContext{
-			int k = i; // compile-time error
-			int m = l; // ok
-		}
-	}
-	
-void foo() {
-	class Local { // a local class
-		int j = i;
-		}
-	}
-}
-
- -

The declaration of class LocalInStaticContext occurs in a static context-within the static method classMethod. Instance variables of class Outer are not available within the body of a static method. In particular, instance variables of Outer are not available inside the body of LocalInStaticContext. However, local variables from the surrounding method may be referred to without error (provided they are marked final).

- -

Inner classes whose declarations do not occur in a static context may freely refer to the instance variables of their enclosing class. An instance variable is always defined with respect to an instance. In the case of instance variables of an enclosing class, the instance variable must be defined with respect to an enclosing instance of that class. So, for example, the class Local above has an enclosing instance of class Outer. As a further example:

- -
-class WithDeepNesting{
-	boolean toBe;
-	WithDeepNesting(boolean b) { toBe = b;}
-	class Nested {
-		boolean theQuestion;
-		class DeeplyNested {
-			DeeplyNested(){
-				theQuestion = toBe || !toBe;
-			}
-		}
-	}
-}
-
-Here, every instance of WithDeepNesting.Nested.DeeplyNested has an enclosing instance of class WithDeepNesting.Nested (its immediately enclosing instance) and an enclosing instance of class WithDeepNesting (its 2nd lexically enclosing instance).

- -

- -

- -

- - -

8.1.4 Superclasses and Subclasses

- -The optional extends clause in a normal class declaration specifies the direct superclass of the current class.

-

-Super:
-	extends ClassType
-	
-
-The following is repeated from §4.3 to make the presentation here clearer:

-

-
-ClassType:
-	TypeDeclSpecifier TypeArgumentsopt
-
-A class is said to be a direct subclass of its direct superclass. The direct superclass is the class from whose implementation the implementation of the current class is derived. The direct superclass of an enum type E is Enum<E>. The extends clause must not appear in the definition of the class Object, because it is the primordial class and has no direct superclass.

- -Given a (possibly generic) class declaration for C<F1,...,Fn>, n0, CObject, the direct superclass of the class type (§4.5) C<F1,...,Fn> is the type given in the extends clause of the declaration of C if an extends clause is present, or Object otherwise.

- -Let C<F1,...,Fn>, n>0, be a generic class declaration. The direct superclass of the parameterized class type C<T1,...,Tn> , where Ti, 1in, is a type, is D<U1 theta , ..., Uk theta>, where D<U1,...,Uk> is the direct superclass of C<F1,...,Fn>, and theta is the substitution [F1 := T1, ..., Fn := Tn].

- -The ClassType must name an accessible (§6.6) class type, or a compile-time error occurs. If the specified ClassType names a class that is final (§8.1.1.2), then a compile-time error occurs; final classes are not allowed to have subclasses. It is a compile-time error if the ClassType names the class Enum or any invocation of it. If the TypeName is followed by any type arguments, it must be a correct invocation of the type declaration denoted by TypeName, and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.

- -

In the example:

-
class Point { int x, y; }
-final class ColoredPoint extends Point { int color; }
-class Colored3DPoint extends ColoredPoint { int z; } // error
-
-the relationships are as follows:

-

-The declaration of class Colored3dPoint causes a compile-time error because it attempts to extend the final class ColoredPoint.

- -

- -The subclass relationship is the transitive closure of the direct subclass relationship. A class A is a subclass of class C if either of the following is true:

-

-Class C is said to be a superclass of class A whenever A is a subclass of C.

- -

In the example:

-
class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-final class Colored3dPoint extends ColoredPoint { int z; }
-
-the relationships are as follows:

-

-A class C directly depends on a type T if T is mentioned in the extends or implements clause of C either as a superclass or superinterface, or as a qualifier of a superclass or superinterface name. A class C depends on a reference type T if any of the following conditions hold:

-

-It is a compile-time error if a class depends on itself.

- -

For example:

-
class Point extends ColoredPoint { int x, y; }
-class ColoredPoint extends Point { int color; }
-
-causes a compile-time error.

- -If circularly declared classes are detected at run time, as classes are loaded (§12.2), then a ClassCircularityError is thrown.

- - -

8.1.5 Superinterfaces

- -The optional implements clause in a class declaration lists the names of interfaces that are direct superinterfaces of the class being declared:

-

-Interfaces:
-	implements InterfaceTypeList
-
-InterfaceTypeList:
-	InterfaceType
-	InterfaceTypeList , InterfaceType
-	
-
-The following is repeated from §4.3 to make the presentation here clearer:

-


-InterfaceType:
-	TypeDeclSpecifier TypeArgumentsopt
-
-Given a (possibly generic) class declaration for C<F1,...,Fn>, n0, CObject, the direct superinterfaces of the class type (§4.5) C<F1,...,Fn> are the types given in the implements clause of the declaration of C if an implements clause is present.

- -Let C<F1,...,Fn>, n>0, be a generic class declaration. The direct superinterfaces of the parameterized class type C<T1,...,Tn>, where Ti, 1in, is a type, are all types I<U1 theta , ..., Uk theta>, where I<U1,...,Uk> is a direct superinterface of C<F1,...,Fn>, and theta is the substitution [F1 := T1, ..., Fn := Tn].

- -Each InterfaceType must name an accessible (§6.6) interface type, or a compile-time error occurs. If the TypeName is followed by any type arguments, it must be a correct invocation of the type declaration denoted by TypeName, and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.

- -A compile-time error occurs if the same interface is mentioned as a direct superinterface two or more times in a single implements clause names.

- -

This is true even if the interface is named in different ways; for example, the code:

- -

-
class Redundant implements java.lang.Cloneable, Cloneable {
-	int x;
-}
-
-results in a compile-time error because the names java.lang.Cloneable and Cloneable refer to the same interface.

- -An interface type I is a superinterface of class type C if any of the following is true:

-

-A class is said to implement all its superinterfaces.

- -

In the example:

-
public interface Colorable {
-	void setColor(int color);
-	int getColor();
-}
-public enum Finish {MATTE, GLOSSY}
-public interface Paintable extends Colorable {
-	void setFinish(Finish finish);
-	Finish getFinish();
-}
-class Point { int x, y; }
-class ColoredPoint extends Point implements Colorable {
-	int color;
-	public void setColor(int color) { this.color = color; }
-	public int getColor() { return color; }
-}
-class PaintedPoint extends ColoredPoint implements Paintable
-{
-	Finish finish;
-	public void setFinish(Finish finish) {
-		this.finish = finish;
-	}
-	public Finish getFinish() { return finish; }
-}
-
-the relationships are as follows:

-

-A class can have a superinterface in more than one way. In this example, the class PaintedPoint has Colorable as a superinterface both because it is a superinterface of ColoredPoint and because it is a superinterface of Paintable. Unless the class being declared is abstract, the declarations of all the method members of each direct superinterface must be implemented either by a declaration in this class or by an existing method declaration inherited from the direct superclass, because a class that is not abstract is not permitted to have abstract methods (§8.1.1.1).

- -

Thus, the example:

-
interface Colorable {
-	void setColor(int color);
-	int getColor();
-}
-class Point { int x, y; };
-class ColoredPoint extends Point implements Colorable {
-	int color;
-}
-
-causes a compile-time error, because ColoredPoint is not an abstract class but it fails to provide an implementation of methods setColor and getColor of the interface Colorable.

- -

It is permitted for a single method declaration in a class to implement methods of more than one superinterface. For example, in the code:

-
interface Fish { int getNumberOfScales(); }
-interface Piano { int getNumberOfScales(); }
-class Tuna implements Fish, Piano {
-	// You can tune a piano, but can you tuna fish?
-	int getNumberOfScales() { return 91; }
-}
-
-the method getNumberOfScales in class Tuna has a name, signature, and return type that matches the method declared in interface Fish and also matches the method declared in interface Piano; it is considered to implement both.

- -

On the other hand, in a situation such as this:

-
interface Fish { int getNumberOfScales(); }
-interface StringBass { double getNumberOfScales(); }
-class Bass implements Fish, StringBass {
-	// This declaration cannot be correct, no matter what type is used.
-	public ??? getNumberOfScales() { return 91; }
-}
-
-It is impossible to declare a method named getNumberOfScales whose signature and return type are compatible with those of both the methods declared in interface Fish and in interface StringBass, because a class cannot have multiple methods with the same signature and different primitive return types (§8.4). Therefore, it is impossible for a single class to implement both interface Fish and interface StringBass (§8.4.8).

- -A class may not at the same time be a subtype of two interface types which are different invocations of the same generic interface (§9.1.2), or an invocation of a generic interface and a raw type naming that same generic interface.

-


- -

- Discussion -

-

- - Here is an example of an illegal multiple inheritance of an interface:

-

class B implements I<Integer>
-class C extends B implements I<String>
-
-

- - This requirement was introduced in order to support translation by type erasure (§4.6).

- -


-

- - -

8.1.6 Class Body and Member Declarations

- -A class body may contain declarations of members of the class, that is, fields (§8.3), classes (§8.5), interfaces (§8.5) and methods (§8.4). A class body may also contain instance initializers (§8.6), static initializers (§8.7), and declarations of constructors (§8.8) for the class.

-

-
-ClassBody:
-	{ ClassBodyDeclarationsopt }
-
-ClassBodyDeclarations:
-	ClassBodyDeclaration
-	ClassBodyDeclarations ClassBodyDeclaration
-
-ClassBodyDeclaration:
-	ClassMemberDeclaration
-	InstanceInitializer
-	StaticInitializer
-	ConstructorDeclaration
-
-ClassMemberDeclaration:
-	FieldDeclaration
-	MethodDeclaration
-	ClassDeclaration						
-	InterfaceDeclaration
-	;		 
-
-The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, including any nested type declarations.

- -If C itself is a nested class, there may be definitions of the same kind (variable, method, or type) and name as m in enclosing scopes. (The scopes may be blocks, classes, or packages.) In all such cases, the member m declared or inherited in C shadows (§6.3.1) the other definitions of the same kind and name.

- - -

8.2 Class Members

- -The members of a class type are all of the following:

-

-Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

- -We use the phrase the type of a member to denote:

-

-Constructors, static initializers, and instance initializers are not members and therefore are not inherited.

- -

The example:

- -

-
class Point {
-	int x, y;
-	private Point() { reset(); }
-	Point(int x, int y) { this.x = x; this.y = y; }
-	private void reset() { this.x = 0; this.y = 0; }
-}
-class ColoredPoint extends Point {
-	int color;
-	void clear() { reset(); }				// error
-}
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint c = new ColoredPoint(0, 0);	// error
-		c.reset();					// error
-	}
-}
-
-causes four compile-time errors:

-

-

-Two more errors occur because the method reset of class Point is private, and therefore is not inherited by class ColoredPoint. The method invocations in method clear of class ColoredPoint and in method main of class Test are therefore not correct.

- - -

8.2.1 Examples of Inheritance

- -This section illustrates inheritance of class members through several examples.

- - -

8.2.1.1 Example: Inheritance with Default Access

- -Consider the example where the points package declares two compilation units:

-

package points;
-public class Point {
-	int x, y;
-	public void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-and:

-

package points;
-public class Point3d extends Point {
-	int z;
-	public void move(int dx, int dy, int dz) {
-		x += dx; y += dy; z += dz;
-	}
-}
-
-and a third compilation unit, in another package, is:

-

import points.Point3d;
-class Point4d extends Point3d {
-	int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		x += dx; y += dy; z += dz; w += dw; // compile-time errors
-	}
-}
-
-Here both classes in the points package compile. The class Point3d inherits the fields x and y of class Point, because it is in the same package as Point. The class Point4d, which is in a different package, does not inherit the fields x and y of class Point or the field z of class Point3d, and so fails to compile.

- -

A better way to write the third compilation unit would be:

-
import points.Point3d;
-class Point4d extends Point3d {
-	int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		super.move(dx, dy, dz); w += dw;
-	}
-}
-
-using the move method of the superclass Point3d to process dx, dy, and dz. If Point4d is written in this way it will compile without errors.

- - -

8.2.1.2 Inheritance with public and protected

- -Given the class Point:

-

package points;
-public class Point {
-	public int x, y;
-	protected int useCount = 0;
-	static protected int totalUseCount = 0;
-	public void move(int dx, int dy) {
-		x += dx; y += dy; useCount++; totalUseCount++;
-	}
-}
-
-the public and protected fields x, y, useCount and totalUseCount are inherited in all subclasses of Point.

- -

Therefore, this test program, in another package, can be compiled successfully:

-
class Test extends points.Point {
-	public void moveBack(int dx, int dy) {
-		x -= dx; y -= dy; useCount++; totalUseCount++;
-	}
-}
-
- -

8.2.1.3 Inheritance with private

- -In the example:

-

class Point {
-	int x, y;
-	void move(int dx, int dy) {
-		x += dx; y += dy; totalMoves++;
-	}
-	private static int totalMoves;
-	void printMoves() { System.out.println(totalMoves); }
-}
-
-

- -

-

class Point3d extends Point {
-	int z;
-	void move(int dx, int dy, int dz) {
-		super.move(dx, dy); z += dz; totalMoves++;
-	}
-}
-
-the class variable totalMoves can be used only within the class Point; it is not inherited by the subclass Point3d. A compile-time error occurs because method move of class Point3d tries to increment totalMoves.

- - -

8.2.1.4 Accessing Members of Inaccessible Classes

- -Even though a class might not be declared public, instances of the class might be available at run time to code outside the package in which it is declared by means a public superclass or superinterface. An instance of the class can be assigned to a variable of such a public type. An invocation of a public method of the object referred to by such a variable may invoke a method of the class if it implements or overrides a method of the public superclass or superinterface. (In this situation, the method is necessarily declared public, even though it is declared in a class that is not public.)

- -

Consider the compilation unit:

-
package points;
-public class Point {
-	public int x, y;
-	public void move(int dx, int dy) {
-		x += dx; y += dy;
-	}
-}
-
-and another compilation unit of another package:

-

package morePoints;
-class Point3d extends points.Point {
-	public int z;
-	public void move(int dx, int dy, int dz) {
-		super.move(dx, dy); z += dz;
-	}
-	public void move(int dx, int dy) {
-		move(dx, dy, 0);
-	}
-}
-
-

-

public class OnePoint {
-	public static points.Point getOne() { 
-		return new Point3d(); 
-	}
-}
-
-

- -An invocation morePoints.OnePoint.getOne() in yet a third package would return a Point3d that can be used as a Point, even though the type Point3d is not available outside the package morePoints. The two argument version of method move could then be invoked for that object, which is permissible because method move of Point3d is public (as it must be, for any method that overrides a public method must itself be public, precisely so that situations such as this will work out correctly). The fields x and y of that object could also be accessed from such a third package.

- -

While the field z of class Point3d is public, it is not possible to access this field from code outside the package morePoints, given only a reference to an instance of class Point3d in a variable p of type Point. This is because the expression p.z is not correct, as p has type Point and class Point has no field named z; also, the expression ((Point3d)p).z is not correct, because the class type Point3d cannot be referred to outside package morePoints.

- -

The declaration of the field z as public is not useless, however. If there were to be, in package morePoints, a public subclass Point4d of the class Point3d:

-
package morePoints;
-public class Point4d extends Point3d {
-	public int w;
-	public void move(int dx, int dy, int dz, int dw) {
-		super.move(dx, dy, dz); w += dw;
-	}
-}
-
-

- -then class Point4d would inherit the field z, which, being public, could then be accessed by code in packages other than morePoints, through variables and expressions of the public type Point4d.

- -

- -

- -

- - -

8.3 Field Declarations

- -The variables of a class type are introduced by field declarations:

-

-
-FieldDeclaration:
-	FieldModifiersopt Type VariableDeclarators ;
-
-VariableDeclarators:
-	VariableDeclarator
-	VariableDeclarators , VariableDeclarator
-
-VariableDeclarator:
-	VariableDeclaratorId
-	VariableDeclaratorId = VariableInitializer
-
-VariableDeclaratorId:
-	Identifier
-	VariableDeclaratorId [ ]
-
-VariableInitializer:
-	Expression
-	ArrayInitializer
-
-
-The FieldModifiers are described in §8.3.1. The Identifier in a FieldDeclarator may be used in a name to refer to the field. Fields are members; the scope (§6.3) of a field declaration is specified in §8.1.6. More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration. Variable declarations involving array types are discussed in §10.2.

- -It is a compile-time error for the body of a class declaration to declare two fields with the same name. Methods, types, and fields may have the same name, since they are used in different contexts and are disambiguated by different lookup procedures (§6.5).

- -If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class. The field declaration also shadows (§6.3.1) declarations of any accessible fields in enclosing classes or interfaces, and any local variables, formal method parameters, and exception handler parameters with the same name in any enclosing blocks.

- -If a field declaration hides the declaration of another field, the two fields need not have the same type.

- -A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

- -

Note that a private field of a superclass might be accessible to a subclass (for example, if both classes are members of the same class). Nevertheless, a private field is never inherited by a subclass.

- -

It is possible for a class to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.

- -

There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.

- -

A hidden field can be accessed by using a qualified name (if it is static) or by using a field access expression (§15.11) that contains the keyword super or a cast to a superclass type. See §15.11.2 for discussion and an example.

- -

A value stored in a field of type float is always an element of the float value set (§4.2.3); similarly, a value stored in a field of type double is always an element of the double value set. It is not permitted for a field of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a field of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.

- - -

8.3.1 Field Modifiers

-
-FieldModifiers:
-	FieldModifier
-	FieldModifiers FieldModifier
-
-FieldModifier: one of
-	Annotation public protected private
-	static final transient volatile
-
-The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a field declaration, or if a field declaration has more than one of the access modifiers public, protected, and private.

- -If an annotation a on a field declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.FIELD, or a compile-time error occurs. Annotation modifiers are described further in §9.7.

- -

If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.

- - -

8.3.1.1 static Fields

- -If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

- -A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses. The example program:

-

class Point {
-	int x, y, useCount;
-	Point(int x, int y) { this.x = x; this.y = y; }
-	final static Point origin = new Point(0, 0);
-}
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point(1,1);
-		Point q = new Point(2,2);
-		p.x = 3; p.y = 3; p.useCount++; p.origin.useCount++;
-		System.out.println("(" + q.x + "," + q.y + ")");
-		System.out.println(q.useCount);
-		System.out.println(q.origin == Point.origin);
-		System.out.println(q.origin.useCount);
-	}
-}
-
-prints:

-

(2,2)
-0
-true
-1
-
-showing that changing the fields x, y, and useCount of p does not affect the fields of q, because these fields are instance variables in distinct objects. In this example, the class variable origin of the class Point is referenced both using the class name as a qualifier, in Point.origin, and using variables of the class type in field access expressions (§15.11), as in p.origin and q.origin. These two ways of accessing the origin class variable access the same object, evidenced by the fact that the value of the reference equality expression (§15.21.3):

-

q.origin==Point.origin
-
-is true. Further evidence is that the incrementation:

-

p.origin.useCount++;
-
-causes the value of q.origin.useCount to be 1; this is so because p.origin and q.origin refer to the same variable.

- - -

8.3.1.2 final Fields

- -A field can be declared final (§4.12.4). Both class and instance variables (static and non-static fields) may be declared final.

- -It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.

- -A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.

- - -

8.3.1.3 transient Fields

- -Variables may be marked transient to indicate that they are not part of the persistent state of an object.

- -

If an instance of the class Point:

-
class Point {
-	int x, y;
-	transient float rho, theta;
-}
-
-were saved to persistent storage by a system service, then only the fields x and y would be saved. This specification does not specify details of such services; see the specification of java.io.Serializable for an example of such a service.

- - -

8.3.1.4 volatile Fields

- -As described in §17, the Java programming language allows threads to access shared variables. As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

- -

The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.

- -A field may be declared volatile, in which case the Java memory model (§17) ensures that all threads see a consistent value for the variable.

- -

If, in the following example, one thread repeatedly calls the method one (but no more than Integer.MAX_VALUE times in all), and another thread repeatedly calls the method two:

-
class Test {
-	static int i = 0, j = 0;
-	static void one() { i++; j++; }
-	static void two() {
-		System.out.println("i=" + i + " j=" + j);
-	}
-}
-
-then method two could occasionally print a value for j that is greater than the value of i, because the example includes no synchronization and, under the rules explained in §17, the shared values of i and j might be updated out of order.

- -

One way to prevent this out-or-order behavior would be to declare methods one and two to be synchronized (§8.4.3.6):

-
class Test {
-	static int i = 0, j = 0;
-	static synchronized void one() { i++; j++; }
-	static synchronized void two() {
-		System.out.println("i=" + i + " j=" + j);
-	}
-}
-
-This prevents method one and method two from being executed concurrently, and furthermore guarantees that the shared values of i and j are both updated before method one returns. Therefore method two never observes a value for j greater than that for i; indeed, it always observes the same value for i and j.

- -

Another approach would be to declare i and j to be volatile:

-
class Test {
-	static volatile int i = 0, j = 0;
-	static void one() { i++; j++; }
-	static void two() {
-		System.out.println("i=" + i + " j=" + j);
-	}
-}
-
- -

This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, the shared value for j is never greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j.

-

-See §17 for more discussion and examples.

- -A compile-time error occurs if a final variable is also declared volatile.

- - -

8.3.2 Initialization of Fields

- -If a field declarator contains a variable initializer, then it has the semantics of an assignment (§15.26) to the declared variable, and:

-

class Point {
-	int x = 1, y = 5;
-}
-class Test {
-	public static void main(String[] args) {
-		Point p = new Point();
-		System.out.println(p.x + ", " + p.y);
-	}
-}
-
-produces the output:

-

1, 5
-
-because the assignments to x and y occur whenever a new Point is created.

- -Variable initializers are also used in local variable declaration statements (§14.4), where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.

- -It is a compile-time error if the evaluation of a variable initializer for a static field of a named class (or of an interface) can complete abruptly with a checked exception (§11.2).

- -It is compile-time error if an instance variable initializer of a named class can throw a checked exception unless that exception or one of its supertypes is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor. An instance variable initializer in an anonymous class (§15.9.5) can throw any exceptions.

- -

- - -

8.3.2.1 Initializers for Class Variables

- -If a reference by simple name to any instance variable occurs in an initialization expression for a class variable, then a compile-time error occurs.

- -If the keyword this (§15.8.3) or the keyword super (§15.11.2, §15.12) occurs in an initialization expression for a class variable, then a compile-time error occurs.

- -

One subtlety here is that, at run time, static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (§9.3.1). These variables are "constants" that will never be observed to have their default initial values (§4.12.5), even by devious programs. See §12.4.2 and §13.4.9 for more discussion.

- -Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to class variables.

- - -

8.3.2.2 Initializers for Instance Variables

- -Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later.

- -

Thus the example:

-
class Test {
-	float f = j;
-	static int j = 1;
-}
-
-compiles without error; it initializes j to 1 when class Test is initialized, and initializes f to the current value of j every time an instance of class Test is created.

- -Initialization expressions for instance variables are permitted to refer to the current object this (§15.8.3) and to use the keyword super (§15.11.2, §15.12).

- -Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to instance variables.

- - -

8.3.2.3 Restrictions on the use of Fields during Initialization

- -The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

-

-A compile-time error occurs if any of the four requirements above are not met.

- -

This means that a compile-time error results from the test program:

-
	class Test {
-		int i = j;	// compile-time error: incorrect forward reference
-		int j = 1;
-	}
-
-whereas the following example compiles without error:

-

	class Test {
-		Test() { k = 2; }
-		int j = 1;
-		int i = j;
-		int k;
-	}
-
-even though the constructor (§8.8) for Test refers to the field k that is declared three lines later.

- -

These restrictions are designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:

-
class Z {
-	static int i = j + 2; 
-	static int j = 4;
-}
-
-and:

-

class Z {
-	static { i = j + 2; }
-	static int i, j;
-	static { j = 4; }
-}
-
-result in compile-time errors. Accesses by methods are not checked in this way, so:

-

class Z {
-	static int peek() { return j; }
-	static int i = peek();
-	static int j = 1;
-}
-class Test {
-	public static void main(String[] args) {
-		System.out.println(Z.i);
-	}
-}
-
-produces the output:

-

0
-
-because the variable initializer for i uses the class method peek to access the value of the variable j before j has been initialized by its variable initializer, at which point it still has its default value (§4.12.5).

- -

A more elaborate example is:

-
class UseBeforeDeclaration {
-	static {
-		x = 100; // ok - assignment
-		int y = x + 1; // error - read before declaration
-		int v = x = 3; // ok - x at left hand side of assignment
-		int z = UseBeforeDeclaration.x * 2; 
-	// ok - not accessed via simple name
-		Object o = new Object(){ 
-			void foo(){x++;} // ok - occurs in a different class
-			{x++;} // ok - occurs in a different class
-    		};
-  }
-	{
-		j = 200; // ok - assignment
-		j = j + 1; // error - right hand side reads before declaration
-		int k = j = j + 1; 
-		int n = j = 300; // ok - j at left hand side of assignment
-		int h = j++; // error - read before declaration
-		int l = this.j * 3; // ok - not accessed via simple name
-		Object o = new Object(){ 
-			void foo(){j++;} // ok - occurs in a different class
-			{ j = j + 1;} // ok - occurs in a different class
-		};
-	}
-	int w = x = 3; // ok - x at left hand side of assignment
-	int p = x; // ok - instance initializers may access static fields
-	static int u = (new Object(){int bar(){return x;}}).bar();
-	// ok - occurs in a different class
-	static int x;
-	int m = j = 4; // ok - j at left hand side of assignment
-	int o = (new Object(){int bar(){return j;}}).bar(); 
-	// ok - occurs in a different class
-	int j;
-}
-
- -

8.3.3 Examples of Field Declarations

- -The following examples illustrate some (possibly subtle) points about field declarations.

- - -

8.3.3.1 Example: Hiding of Class Variables

- -The example:

-

class Point {
-	static int x = 2;
-}
-class Test extends Point {
-	static double x = 4.7;
-	public static void main(String[] args) {
-		new Test().printX();
-	}
-	void printX() {
-		System.out.println(x + " " + super.x);
-	}
-}
-
-produces the output:

-

4.7 2
-
-because the declaration of x in class Test hides the definition of x in class Point, so class Test does not inherit the field x from its superclass Point. Within the declaration of class Test, the simple name x refers to the field declared within class Test. Code in class Test may refer to the field x of class Point as super.x (or, because x is static, as Point.x). If the declaration of Test.x is deleted:

-

class Point {
-	static int x = 2;
-}
-class Test extends Point {
-	public static void main(String[] args) {
-		new Test().printX();
-	}
-	void printX() {
-		System.out.println(x + " " + super.x);
-	}
-}
-
-then the field x of class Point is no longer hidden within class Test; instead, the simple name x now refers to the field Point.x. Code in class Test may still refer to that same field as super.x. Therefore, the output from this variant program is:

-

2 2
-
- -

8.3.3.2 Example: Hiding of Instance Variables

- -This example is similar to that in the previous section, but uses instance variables rather than static variables. The code:

-

class Point {
-	int x = 2;
-}
-class Test extends Point {
-	double x = 4.7;
-	void printBoth() {
-		System.out.println(x + " " + super.x);
-	}
-	public static void main(String[] args) {
-		Test sample = new Test();
-		sample.printBoth();
-		System.out.println(sample.x + " " + 
-												((Point)sample).x);
-	}
-}
-
-produces the output:

-

4.7 2
-4.7 2
-
-because the declaration of x in class Test hides the definition of x in class Point, so class Test does not inherit the field x from its superclass Point. It must be noted, however, that while the field x of class Point is not inherited by class Test, it is nevertheless implemented by instances of class Test. In other words, every instance of class Test contains two fields, one of type int and one of type double. Both fields bear the name x, but within the declaration of class Test, the simple name x always refers to the field declared within class Test. Code in instance methods of class Test may refer to the instance variable x of class Point as super.x.

- -

Code that uses a field access expression to access field x will access the field named x in the class indicated by the type of reference expression. Thus, the expression sample.x accesses a double value, the instance variable declared in class Test, because the type of the variable sample is Test, but the expression ((Point)sample).x accesses an int value, the instance variable declared in class Point, because of the cast to type Point.

- -

If the declaration of x is deleted from class Test, as in the program:

-
class Point {
-	static int x = 2;
-}
-class Test extends Point {
-	void printBoth() {
-		System.out.println(x + " " + super.x);
-	}
-	public static void main(String[] args) {
-		Test sample = new Test();
-		sample.printBoth();
-		System.out.println(sample.x + " " +
-												((Point)sample).x);
-	}
-}
-
-then the field x of class Point is no longer hidden within class Test. Within instance methods in the declaration of class Test, the simple name x now refers to the field declared within class Point. Code in class Test may still refer to that same field as super.x. The expression sample.x still refers to the field x within type Test, but that field is now an inherited field, and so refers to the field x declared in class Point. The output from this variant program is:

-

2 2
-2 2
-
- -

8.3.3.3 Example: Multiply Inherited Fields

- -A class may inherit two or more fields with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited field by its simple name. A qualified name or a field access expression that contains the keyword super (§15.11.2) may be used to access such fields unambiguously. In the example:

-

interface Frob { float v = 2.0f; }
-class SuperTest { int v = 3; }
-class Test extends SuperTest implements Frob {
-	public static void main(String[] args) {
-		new Test().printV();
-	}
-	void printV() { System.out.println(v); }
-}
-
-the class Test inherits two fields named v, one from its superclass SuperTest and one from its superinterface Frob. This in itself is permitted, but a compile-time error occurs because of the use of the simple name v in method printV: it cannot be determined which v is intended.

- -

The following variation uses the field access expression super.v to refer to the field named v declared in class SuperTest and uses the qualified name Frob.v to refer to the field named v declared in interface Frob:

-
interface Frob { float v = 2.0f; }
-class SuperTest { int v = 3; }
-class Test extends SuperTest implements Frob {
-	public static void main(String[] args) {
-		new Test().printV();
-	}
-	void printV() {
-		System.out.println((super.v + Frob.v)/2);
-	}
-}
-
-It compiles and prints:

-

2.5
-
- -

Even if two distinct inherited fields have the same type, the same value, and are both final, any reference to either field by simple name is considered ambiguous and results in a compile-time error. In the example:

-
-interface Color { int RED=0, GREEN=1, BLUE=2; }
-interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; }
-class Test implements Color, TrafficLight {
-	public static void main(String[] args) {
-		System.out.println(GREEN);	// compile-time error
-		System.out.println(RED);	// compile-time error
-	}
-}
-
-it is not astonishing that the reference to GREEN should be considered ambiguous, because class Test inherits two different declarations for GREEN with different values. The point of this example is that the reference to RED is also considered ambiguous, because two distinct declarations are inherited. The fact that the two fields named RED happen to have the same type and the same unchanging value does not affect this judgment.

- - -

8.3.3.4 Example: Re-inheritance of Fields

- -If the same field declaration is inherited from an interface by multiple paths, the field is considered to be inherited only once. It may be referred to by its simple name without ambiguity. For example, in the code:

-

public interface Colorable {
-	int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff;
-}
-public interface Paintable extends Colorable {
-	int MATTE = 0, GLOSSY = 1;
-}
-class Point { int x, y; }
-class ColoredPoint extends Point implements Colorable {
-	. . .
-}
-class PaintedPoint extends ColoredPoint implements Paintable
-{
-	. . .       RED       . . .
-}
-
-the fields RED, GREEN, and BLUE are inherited by the class PaintedPoint both through its direct superclass ColoredPoint and through its direct superinterface Paintable. The simple names RED, GREEN, and BLUE may nevertheless be used without ambiguity within the class PaintedPoint to refer to the fields declared in interface Colorable.

- -

- - -

8.4 Method Declarations

- -A method declares executable code that can be invoked, passing a fixed number of values as arguments.

- -

-

-
-MethodDeclaration:
-	MethodHeader MethodBody
-
-MethodHeader:
-	MethodModifiersopt TypeParametersopt ResultType MethodDeclarator 
-Throwsopt
-ResultType:
-	Type
-	void
-
-MethodDeclarator:
-	Identifier ( FormalParameterListopt )
-	
-
-The MethodModifiers are described in §8.4.3, the TypeParameters clause of a method in §8.4.4, the Throws clause in §8.4.6, and the MethodBody in §8.4.7. A method declaration either specifies the type of value that the method returns or uses the keyword void to indicate that the method does not return a value.

- -The Identifier in a MethodDeclarator may be used in a name to refer to the method. A class can declare a method with the same name as the class or a field, member class or member interface of the class, but this is discouraged as a matter of syle.

- -For compatibility with older versions of the Java platform, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. This is supported by the obsolescent production:

-

-
-MethodDeclarator:
-	MethodDeclarator [ ]
-
-but should not be used in new code.

- -It is a compile-time error for the body of a class to declare as members two methods with override-equivalent signatures (§8.4.2) (name, number of parameters, and types of any parameters). Methods and fields may have the same name, since they are used in different contexts and are disambiguated by different lookup procedures (§6.5).

- - -

8.4.1 Formal Parameters

- -The formal parameters of a method or constructor, if any, are specified by a list of comma-separated parameter specifiers. Each parameter specifier consists of a type (optionally preceded by the final modifier and/or one or more annotations (§9.7)) and an identifier (optionally followed by brackets) that specifies the name of the parameter. The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type:

-

-
-FormalParameterList:
-	LastFormalParameter
-	FormalParameters , LastFormalParameter
-
-FormalParameters:
-	FormalParameter
-	FormalParameters , FormalParameter
-
-FormalParameter:
-	VariableModifiers Type VariableDeclaratorId
-
-VariableModifiers:
-	VariableModifier
-	VariableModifiers VariableModifier
-
-VariableModifier: one of
-	final Annotation
-
-LastFormalParameter:
-	VariableModifiers Type...opt VariableDeclaratorId
-	FormalParameter
-	
-
-The following is repeated from §8.3 to make the presentation here clearer:

-

-
-VariableDeclaratorId:
-	Identifier
-	VariableDeclaratorId [ ]
-
-If a method or constructor has no parameters, only an empty pair of parentheses appears in the declaration of the method or constructor.

- -If two formal parameters of the same method or constructor are declared to have the same name (that is, their declarations mention the same Identifier), then a compile-time error occurs.

- -If an annotation a on a formal parameter corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.PARAMETER, or a compile-time error occurs. Annotation modifiers are described further in §9.7.

- -It is a compile-time error if a method or constructor parameter that is declared final is assigned to within the body of the method or constructor.

- -When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.

- -If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[]. The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation (§15.12.4.2).

- -The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.

- -These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor. However, a parameter of a method or constructor may be shadowed anywhere inside a class declaration nested within that method or constructor. Such a nested class declaration could declare either a local class (§14.3) or an anonymous class (§15.9).

- -Formal parameters are referred to only using simple names, never by using qualified names (§6.6).

- -A method or constructor parameter of type float always contains an element of the float value set (§4.2.3); similarly, a method or constructor parameter of type double always contains an element of the double value set. It is not permitted for a method or constructor parameter of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a method parameter of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.

- -Where an actual argument expression corresponding to a parameter variable is not FP-strict (§15.4), evaluation of that actual argument expression is permitted to use intermediate values drawn from the appropriate extended-exponent value sets. Prior to being stored in the parameter variable the result of such an expression is mapped to the nearest value in the corresponding standard value set by method invocation conversion (§5.3).

- - -

8.4.2 Method Signature

- -It is a compile-time error to declare two methods with override-equivalent signatures (defined below) in a class.

- -Two methods have the same signature if they have the same name and argument types.

- -Two method or constructor declarations M and N have the same argument types if all of the following conditions hold:

-

-The signature of a method m1 is a subsignature of the signature of a method m2 if either

-

- -

-


-

- Discussion -

- - The notion of subsignature defined here is designed to express a relationship between two methods whose signatures are not identical, but in which one may override the other.

- -Specifically, it allows a method whose signature does not use generic types to override any generified version of that method. This is important so that library designers may freely generify methods independently of clients that define subclasses or subinterfaces of the library.

- -Consider the example:

-

class CollectionConverter {
-    List toList(Collection c) {...}
-}
-class Overrider extends CollectionConverter{
-    List toList(Collection c) {...}
-}
-
-Now, assume this code was written before the introduction of genericity, and now the author of class CollectionConverter decides to generify the code, thus:

-

class CollectionConverter {
-	<T> List<T> toList(Collection<T> c) {...}
-}
-
-Without special dispensation, Overrider.toList() would no longer override CollectionConverter.toList(). Instead, the code would be illegal. This would significantly inhibit the use of genericity, since library writers would hesitate to migrate existing code.

-


- -

- -Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.

- -

The example:

-
class Point implements Move {
-	int x, y;
-	abstract void move(int dx, int dy);
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-
-causes a compile-time error because it declares two move methods with the same (and hence, override-equivalent) signature. This is an error even though one of the declarations is abstract.

- - -

8.4.3 Method Modifiers

-
-MethodModifiers:
-	MethodModifier
-	MethodModifiers MethodModifier
-
-MethodModifier: one of
-	Annotation public protected private abstract static
-	final synchronized native strictfp
-
-The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a method declaration, or if a method declaration has more than one of the access modifiers public, protected, and private. A compile-time error occurs if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, strictfp, or synchronized. A compile-time error occurs if a method declaration that contains the keyword native also contains strictfp.

- -If an annotation a on a method declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.METHOD, or a compile-time error occurs. Annotations are discussed further in §9.7.

- -

If two or more method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier.

- - -

8.4.3.1 abstract Methods

- -An abstract method declaration introduces the method as a member, providing its signature (§8.4.2), return type, and throws clause (if any), but does not provide an implementation. The declaration of an abstract method m must appear directly within an abstract class (call it A) unless it occurs within an enum (§8.9); otherwise a compile-time error results. Every subclass of A that is not abstract must provide an implementation for m, or a compile-time error occurs as specified in §8.1.1.1.

- -It is a compile-time error for a private method to be declared abstract.

- -

It would be impossible for a subclass to implement a private abstract method, because private methods are not inherited by subclasses; therefore such a method could never be used.

- -It is a compile-time error for a static method to be declared abstract.

- -It is a compile-time error for a final method to be declared abstract.

- -An abstract class can override an abstract method by providing another abstract method declaration.

- -

This can provide a place to put a documentation comment, to refine the return type, or to declare that the set of checked exceptions (§11.2) that can be thrown by that method, when it is implemented by its subclasses, is to be more limited. For example, consider this code:

- -

-
class BufferEmpty extends Exception {
-	BufferEmpty() { super(); }
-	BufferEmpty(String s) { super(s); }
-}
-class BufferError extends Exception {
-	BufferError() { super(); }
-	BufferError(String s) { super(s); }
-}
-public interface Buffer {
-	char get() throws BufferEmpty, BufferError;
-}
-public abstract class InfiniteBuffer implements Buffer {
-	public abstract char get() throws BufferError;
-}
-
-

- -

The overriding declaration of method get in class InfiniteBuffer states that method get in any subclass of InfiniteBuffer never throws a BufferEmpty exception, putatively because it generates the data in the buffer, and thus can never run out of data.

- -An instance method that is not abstract can be overridden by an abstract method.

- -

- -

For example, we can declare an abstract class Point that requires its subclasses to implement toString if they are to be complete, instantiable classes:

-
abstract class Point {
-	int x, y;
-	public abstract String toString();
-}
-
-This abstract declaration of toString overrides the non-abstract toString method of class Object. (Class Object is the implicit direct superclass of class Point.) Adding the code:

-

class ColoredPoint extends Point {
-	int color;
-	public String toString() {
-		return super.toString() + ": color " + color; // error
-	}
-}
-
-results in a compile-time error because the invocation super.toString() refers to method toString in class Point, which is abstract and therefore cannot be invoked. Method toString of class Object can be made available to class ColoredPoint only if class Point explicitly makes it available through some other method, as in:

-

abstract class Point {
-	int x, y;
-	public abstract String toString();
-	protected String objString() { return super.toString(); }
-}
-class ColoredPoint extends Point {
-	int color;
-	public String toString() {
-		return objString() + ": color " + color;														// correct
-	}
-}
-
- -

8.4.3.2 static Methods

- -A method that is declared static is called a class method. A class method is always invoked without reference to a particular object. An attempt to reference the current object using the keyword this or the keyword super or to reference the type parameters of any surrounding declaration in the body of a class method results in a compile-time error. It is a compile-time error for a static method to be declared abstract.

- -A method that is not declared static is called an instance method, and sometimes called a non-static method. An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

- - -

8.4.3.3 final Methods

- -A method can be declared final to prevent subclasses from overriding or hiding it. It is a compile-time error to attempt to override or hide a final method.

- -A private method and all methods declared immediately within a final class (§8.1.1.2) behave as if they are final, since it is impossible to override them.

- -It is a compile-time error for a final method to be declared abstract.

- -At run time, a machine-code generator or optimizer can "inline" the body of a final method, replacing an invocation of the method with the code in its body. The inlining process must preserve the semantics of the method invocation. In particular, if the target of an instance method invocation is null, then a NullPointerException must be thrown even if the method is inlined. The compiler must ensure that the exception will be thrown at the correct point, so that the actual arguments to the method will be seen to have been evaluated in the correct order prior to the method invocation.

- -

Consider the example:

-
final class Point {
-	int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-class Test {
-	public static void main(String[] args) {
-		Point[] p = new Point[100];
-		for (int i = 0; i < p.length; i++) {
-			p[i] = new Point();
-			p[i].move(i, p.length-1-i);
-		}
-	}
-}
-
-Here, inlining the method move of class Point in method main would transform the for loop to the form:

-

		for (int i = 0; i < p.length; i++) {
-			p[i] = new Point();
-			Point pi = p[i];
-			int j = p.length-1-i;
-			pi.x += i;
-			pi.y += j;
-		}
-
-The loop might then be subject to further optimizations.

- -

Such inlining cannot be done at compile time unless it can be guaranteed that Test and Point will always be recompiled together, so that whenever Point-and specifically its move method-changes, the code for Test.main will also be updated.

- - -

8.4.3.4 native Methods

- -A method that is native is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN,or assembly language. The body of a native method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.

- -A compile-time error occurs if a native method is declared abstract.

- -

For example, the class RandomAccessFile of the package java.io might declare the following native methods:

-
package java.io;
-public class RandomAccessFile
-	implements DataOutput, DataInput
-{	. . .
-	public native void open(String name, boolean writeable)
-		throws IOException;
-	public native int readBytes(byte[] b, int off, int len)
-		throws IOException;
-	public native void writeBytes(byte[] b, int off, int len)
-		throws IOException;
-	public native long getFilePointer() throws IOException;
-	public native void seek(long pos) throws IOException;
-	public native long length() throws IOException;
-	public native void close() throws IOException;
-
-

}

-
- -

8.4.3.5 strictfp Methods

- -The effect of the strictfp modifier is to make all float or double expressions within the method body be explicitly FP-strict (§15.4).

- - -

8.4.3.6 synchronized Methods

- -A synchronized method acquires a monitor (§17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

- -

These are the same locks that can be used by the synchronized statement (§14.19); thus, the code:

-
class Test {
-	int count;
-	synchronized void bump() { count++; }
-	static int classCount;
-	static synchronized void classBump() {
-		classCount++;
-	}
-}
-
-has exactly the same effect as:

-

class BumpTest {
-	int count;
-	void bump() {
-		synchronized (this) {
-			count++;
-		}
-	}
-	static int classCount;
-	static void classBump() {
-		try {
-			synchronized (Class.forName("BumpTest")) {
-				classCount++;
-			}
-		} catch (ClassNotFoundException e) {
-				...
-		}
-	}
-}
-
-The more elaborate example:

-

public class Box {
-	private Object boxContents;
-	public synchronized Object get() {
-		Object contents = boxContents;
-		boxContents = null;
-		return contents;
-	}
-	public synchronized boolean put(Object contents) {
-		if (boxContents != null)
-			return false;
-		boxContents = contents;
-		return true;
-	}
-}
-
-defines a class which is designed for concurrent use. Each instance of the class Box has an instance variable boxContents that can hold a reference to any object. You can put an object in a Box by invoking put, which returns false if the box is already full. You can get something out of a Box by invoking get, which returns a null reference if the box is empty.

- -

If put and get were not synchronized, and two threads were executing methods for the same instance of Box at the same time, then the code could misbehave. It might, for example, lose track of an object because two invocations to put occurred at the same time.

- -See §17 for more discussion of threads and locks.

- -

- - -

8.4.4 Generic Methods

- -A method is generic if it declares one or more type variables (§4.4). These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface, as described in §8.1.2.

- -The scope of a method's type parameter is the entire declaration of the method, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

- -Type parameters of generic methods need not be provided explicitly when a generic method is invoked. Instead, they are almost always inferred as specified in §15.12.2.7

- - -

8.4.5 Method Return Type

- -The return type of a method declares the type of value a method returns, if it returns a value, or states that the method is void.

- -A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:

-

- -

-


-

- Discussion -

- - The notion of return-type substitutability summarizes the ways in which return types may vary among methods that override each other.

-

-Note that this definition supports covariant returns - that is, the specialization of the return type to a subtype (but only for reference types).

- -Also note that unchecked conversions are allowed as well. This is unsound, and requires an unchecked warning whenever it is used; it is a special allowance is made to allow smooth migration from non-generic to generic code.

-


- -

- - -

8.4.6 Method Throws

- -A throws clause is used to declare any checked exceptions (§11.2) that can result from the execution of a method or constructor:

-

-
-Throws:
-	throws ExceptionTypeList
-
-ExceptionTypeList:
-	ExceptionType
-	ExceptionTypeList , ExceptionType
-
-ExceptionType:
-	ClassType
-	TypeVariable
-	
-
-A compile-time error occurs if any ExceptionType mentioned in a throws clause is not a subtype (§4.10) of Throwable. It is permitted but not required to mention other (unchecked) exceptions in a throws clause.

- -For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a supertype of that exception type is mentioned in a throws clause in the declaration of the method or constructor.

- -

The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a throws clause. The Java programming language thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.

- -The predefined exceptions that are not checked in this way are those for which declaring every possible occurrence would be unimaginably inconvenient:

-

-A method that overrides or hides another method (§8.4.8), including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.

- -More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. If n has a throws clause that mentions any checked exception types, then m must have a throws clause, and for every checked exception type listed in the throws clause of n, that same exception class or one of its supertypes must occur in the erasure of the throws clause of m; otherwise, a compile-time error occurs.

- -If the unerased throws clause of m does not contain a supertype of each exception type in the throws clause of n, an unchecked warning must be issued.

- -


-

- Discussion -

- See §11 for more information about exceptions and a large example.

- - Type variables are allowed in throws lists even though they are not allowed in catch clauses.

-

interface PrivilegedExceptionAction<E extends Exception> { 
-  void run() throws E;
-} 
-class AccessController {
-  public static <E extends Exception> 
-  Object doPrivileged(PrivilegedExceptionAction<E> action) throws E 
-  { ... }
-}
-class Test {
-  public static void main(String[] args) {
-    try { 
-      AccessController.doPrivileged(
-        new PrivilegedExceptionAction<FileNotFoundException>() { 
-          public void run() throws FileNotFoundException 
-          {... delete a file  ...} 
-        }); 
-    } catch (FileNotFoundException f) {...} // do something 
-  }
-}
-
-
-
-

- -

8.4.7 Method Body

- -A method body is either a block of code that implements the method or simply a semicolon, indicating the lack of an implementation. The body of a method must be a semicolon if and only if the method is either abstract (§8.4.3.1) or native (§8.4.3.4).

-

-MethodBody:
-	Block 
-	;
-
-A compile-time error occurs if a method declaration is either abstract or native and has a block for its body. A compile-time error occurs if a method declaration is neither abstract nor native and has a semicolon for its body.

- -

If an implementation is to be provided for a method declared void, but the implementation requires no executable code, the method body should be written as a block that contains no statements: "{ }".

- -If a method is declared void, then its body must not contain any return statement (§14.17) that has an Expression.

- -If a method is declared to have a return type, then every return statement (§14.17) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.1).

- -

In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body."

- -

Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:

-
class DizzyDean {
-	int pitch() { throw new RuntimeException("90 mph?!"); }
-}
-
- -

8.4.8 Inheritance, Overriding, and Hiding

- -A class C inherits from its direct superclass and direct superinterfaces all non-private methods (whether abstract or not) of the superclass and superinterfaces that are public, protected or declared with default access in the same package as C and are neither overridden (§8.4.8.1) nor hidden (§8.4.8.2) by a declaration in the class.

- - -

8.4.8.1 Overriding (by Instance Methods)

- -An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

-

    - -
  1. C is a subclass of A. - -
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2. - -
  3. Either -
      - -
    • m2 is public, protected or declared with default access in the same package as C, or - -
    • m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2. -
    -
- -Moreover, if m1 is not abstract, then m1 is said to implement any and all declarations of abstract methods that it overrides.

-


-

-Discussion -

- -

- - The signature of an overriding method may differ from the overridden one if a formal parameter in one of the methods has raw type, while the corresponding parameter in the other has a parameterized type.

- -The rules allow the signature of the overriding method to differ from the overridden one, to accommodate migration of pre-existing code to take advantage of genericity. See section §8.4.2 for further analysis.

-


- -

- -A compile-time error occurs if an instance method overrides a static method.

- -

In this respect, overriding of methods differs from hiding of fields (§8.3), for it is permissible for an instance variable to hide a static variable.

- -

An overridden method can be accessed by using a method invocation expression (§15.12) that contains the keyword super. Note that a qualified name or a cast to a superclass type is not effective in attempting to access an overridden method; in this respect, overriding of methods differs from hiding of fields. See §15.12.4.9 for discussion and examples of this point.

- -The presence or absence of the strictfp modifier has absolutely no effect on the rules for overriding methods and implementing abstract methods. For example, it is permitted for a method that is not FP-strict to override an FP-strict method and it is permitted for an FP-strict method to override a method that is not FP-strict.

- -

- - -

8.4.8.2 Hiding (by Class Methods)

- -If a class declares a static method m, then the declaration m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. A compile-time error occurs if a static method hides an instance method.

- -

In this respect, hiding of methods differs from hiding of fields (§8.3), for it is permissible for a static variable to hide an instance variable. Hiding is also distinct from shadowing (§6.3.1) and obscuring (§6.3.2).

- -

A hidden method can be accessed by using a qualified name or by using a method invocation expression (§15.12) that contains the keyword super or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.

- -

- - -

8.4.8.3 Requirements in Overriding and Hiding

- -If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type substitutable for d2, or a compile-time error occurs. Furthermore, if R1 is not a subtype of R2, an unchecked warning must be issued (unless suppressed (§9.6.1.5)).

- -A method declaration must not have a throws clause that conflicts (§8.4.6) with that of any method that it overrides or hides; otherwise, a compile-time error occurs.

-


-

-Discussion -

- -

- - The rules above allow for covariant return types - refining the return type of a method when overriding it.

- -For example, the following declarations are legal although they were illegal in prior versions of the Java programming language:

-

class C implements Cloneable { 
-   C copy() { return (C)clone(); } 
-}
-class D extends C implements Cloneable { 
-   D copy() { return (D)clone(); } 
-}
-
-The relaxed rule for overriding also allows one to relax the conditions on abstract classes implementing interfaces.

-


- -

- -


-

- Discussion -

- -

- Consider

-

class StringSorter {
-// takes a collection of strings and converts it to a sortedlist
-    List toList(Collection c) {...} 
-}
-
- - and assume that someone subclasses StringCollector

-

-class Overrider extends StringSorter{
-    List toList(Collection c) {...}
-}
-
-Now, at some point the author of StringSorter decides to generify the code

-

class StringSorter {
-// takes a collection of strings and converts it to a list
-    List<String> toList(Collection<String> c) {...}
-}
-
-An unchecked warning would be given when compiling Overrider against the new definition of StringSorter because the return type of Overrider.toList() is List, which is not a subtype of the return type of the overridden method, List<String.

-


- -

- -

In these respects, overriding of methods differs from hiding of fields (§8.3), for it is permissible for a field to hide a field of another type.

- -It is a compile time error if a type declaration T has a member method m1 and there exists a method m2 declared in T or a supertype of T such that all of the following conditions hold:

-

-

-


-

-Discussion -

- -

- - These restrictions are necessary because generics are implemented via erasure. The rule above implies that methods declared in the same class with the same name must have different erasures. It also implies that a type declaration cannot implement or extend two distinct invocations of the same generic interface. Here are some further examples.

- -A class cannot have two member methods with the same name and type erasure.

-

class C<T> { T id (T x) {...} }
-class D extends C<String> {
-   Object id(Object x) {...}
-}
-
-This is illegal since D.id(Object) is a member of D, C<String>.id(String) is declared in a supertype of D and:

-

- -

-


- -

- -


-

-Discussion -

-

- Two different methods of a class may not override methods with the same erasure.

-

class C<T> { T id (T x) {...} }
-interface I<T> { Tid(T x); }
-class D extends C<String> implements I<Integer> {
-   String id(String x) {...}
-   Integer id(Integer x) {...}
-}
-
-This is also illegal, since D.id(String) is a member of D, D.id(Integer) is declared in D and:

-

- -

-


- -The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:

-

- -

Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass.

- - -

8.4.8.4 Inheriting Methods with Override-Equivalent Signatures

- -It is possible for a class to inherit multiple methods with override-equivalent (§8.4.2) signatures.

- -It is a compile time error if a class C inherits a concrete method whose signatures is a subsignature of another concrete method inherited by C.

- -


-

- Discussion -

- -

- This can happen, if a superclass is parametric, and it has two methods that were distinct in the generic declaration, but have the same signature in the particular invocation used.

-


- -

- -Otherwise, there are two possible cases:

-

-There might be several paths by which the same method declaration might be inherited from an interface. This fact causes no difficulty and never, of itself, results in a compile-time error.

- - -

8.4.9 Overloading

- -If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name, unless their signatures are override-equivalent.

- -Methods are overridden on a signature-by-signature basis.

- -

If, for example, a class declares two public methods with the same name, and a subclass overrides one of them, the subclass still inherits the other method.

- -

When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).

- - -

8.4.10 Examples of Method Declarations

- -The following examples illustrate some (possibly subtle) points about method declarations.

- - -

8.4.10.1 Example: Overriding

- -In the example:

-

class Point {
-	int x = 0, y = 0;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-class SlowPoint extends Point {
-	int xLimit, yLimit;
-	void move(int dx, int dy) {
-		super.move(limit(dx, xLimit), limit(dy, yLimit));
-	}
-	static int limit(int d, int limit) {
-		return d > limit ? limit : d < -limit ? -limit : d;
-	}
-}
-
-the class SlowPoint overrides the declarations of method move of class Point with its own move method, which limits the distance that the point can move on each invocation of the method. When the move method is invoked for an instance of class SlowPoint, the overriding definition in class SlowPoint will always be called, even if the reference to the SlowPoint object is taken from a variable whose type is Point.

- - -

8.4.10.2 Example: Overloading, Overriding, and Hiding

- -In the example:

-

class Point {
-	int x = 0, y = 0;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	int color;
-}
-class RealPoint extends Point {
-	float x = 0.0f, y = 0.0f;
-	void move(int dx, int dy) { move((float)dx, (float)dy); }
-	void move(float dx, float dy) { x += dx; y += dy; }
-}
-
-the class RealPoint hides the declarations of the int instance variables x and y of class Point with its own float instance variables x and y, and overrides the method move of class Point with its own move method. It also overloads the name move with another method with a different signature (§8.4.2).

- -

In this example, the members of the class RealPoint include the instance variable color inherited from the class Point, the float instance variables x and y declared in RealPoint, and the two move methods declared in RealPoint.

- -

Which of these overloaded move methods of class RealPoint will be chosen for any particular method invocation will be determined at compile time by the overloading resolution procedure described in §15.12.

- - -

8.4.10.3 Example: Incorrect Overriding

- -This example is an extended variation of that in the preceding section:

-

class Point {
-	int x = 0, y = 0, color;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	int getX() { return x; }
-	int getY() { return y; }
-}
-
-

-

class RealPoint extends Point {
-	float x = 0.0f, y = 0.0f;
-	void move(int dx, int dy) { move((float)dx, (float)dy); }
-	void move(float dx, float dy) { x += dx; y += dy; }
-	float getX() { return x; }
-	float getY() { return y; }
-}
-
-Here the class Point provides methods getX and getY that return the values of its fields x and y; the class RealPoint then overrides these methods by declaring methods with the same signature. The result is two errors at compile time, one for each method, because the return types do not match; the methods in class Point return values of type int, but the wanna-be overriding methods in class RealPoint return values of type float.

- - -

8.4.10.4 Example: Overriding versus Hiding

- -This example corrects the errors of the example in the preceding section:

-

class Point {
-	int x = 0, y = 0;
-	void move(int dx, int dy) { x += dx; y += dy; }
-	int getX() { return x; }
-	int getY() { return y; }
-	int color;
-}
-class RealPoint extends Point {
-	float x = 0.0f, y = 0.0f;
-	void move(int dx, int dy) { move((float)dx, (float)dy); }
-	void move(float dx, float dy) { x += dx; y += dy; }
-	int getX() { return (int)Math.floor(x); }
-	int getY() { return (int)Math.floor(y); }
-}
-
-Here the overriding methods getX and getY in class RealPoint have the same return types as the methods of class Point that they override, so this code can be successfully compiled.

- -

- -

- -

Consider, then, this test program:

-
class Test {
-	public static void main(String[] args) {
-		RealPoint rp = new RealPoint();
-		Point p = rp;
-		rp.move(1.71828f, 4.14159f);
-		p.move(1, -1);
-		show(p.x, p.y);
-		show(rp.x, rp.y);
-		show(p.getX(), p.getY());
-		show(rp.getX(), rp.getY());
-	}
-	static void show(int x, int y) {
-		System.out.println("(" + x + ", " + y + ")");
-	}
-	static void show(float x, float y) {
-		System.out.println("(" + x + ", " + y + ")");
-	}
-}
-
-The output from this program is:

-

(0, 0)
-(2.7182798, 3.14159)
-(2, 3)
-(2, 3)
-
- -

The first line of output illustrates the fact that an instance of RealPoint actually contains the two integer fields declared in class Point; it is just that their names are hidden from code that occurs within the declaration of class RealPoint (and those of any subclasses it might have). When a reference to an instance of class RealPoint in a variable of type Point is used to access the field x, the integer field x declared in class Point is accessed. The fact that its value is zero indicates that the method invocation p.move(1, -1) did not invoke the method move of class Point; instead, it invoked the overriding method move of class RealPoint.

- -

The second line of output shows that the field access rp.x refers to the field x declared in class RealPoint. This field is of type float, and this second line of output accordingly displays floating-point values. Incidentally, this also illustrates the fact that the method name show is overloaded; the types of the arguments in the method invocation dictate which of the two definitions will be invoked.

- -

The last two lines of output show that the method invocations p.getX() and rp.getX() each invoke the getX method declared in class RealPoint. Indeed, there is no way to invoke the getX method of class Point for an instance of class RealPoint from outside the body of RealPoint, no matter what the type of the variable we may use to hold the reference to the object. Thus, we see that fields and methods behave differently: hiding is different from overriding.

- - -

8.4.10.5 Example: Invocation of Hidden Class Methods

- -A hidden class (static) method can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods. The example:

-

class Super {
-	static String greeting() { return "Goodnight"; }
-	String name() { return "Richard"; }
-}
-class Sub extends Super {
-	static String greeting() { return "Hello"; }
-	String name() { return "Dick"; }
-}
-class Test {
-	public static void main(String[] args) {
-		Super s = new Sub();
-		System.out.println(s.greeting() + ", " + s.name());
-	}
-}
-
-produces the output:

-

Goodnight, Dick
-
-because the invocation of greeting uses the type of s, namely Super, to figure out, at compile time, which class method to invoke, whereas the invocation of name uses the class of s, namely Sub, to figure out, at run time, which instance method to invoke.

- - -

8.4.10.6 Large Example of Overriding

- -Overriding makes it easy for subclasses to extend the behavior of an existing class, as shown in this example:

-

import java.io.OutputStream;
-import java.io.IOException;
-class BufferOutput {
-	private OutputStream o;
-	BufferOutput(OutputStream o) { this.o = o; }
-	protected byte[] buf = new byte[512];
-	protected int pos = 0;
-	public void putchar(char c) throws IOException {
-		if (pos == buf.length)
-			flush();
-		buf[pos++] = (byte)c;
-	}
-	public void putstr(String s) throws IOException {
-		for (int i = 0; i < s.length(); i++)
-			putchar(s.charAt(i));
-	}
-	public void flush() throws IOException {
-		o.write(buf, 0, pos);
-		pos = 0;
-	}
-}
-class LineBufferOutput extends BufferOutput {
-	LineBufferOutput(OutputStream o) { super(o); }
-	public void putchar(char c) throws IOException {
-		super.putchar(c);
-		if (c == '\n')
-			flush();
-	}
-}
-class Test {
-	public static void main(String[] args)
-		throws IOException
-	{
-		LineBufferOutput lbo =
-			new LineBufferOutput(System.out);
-		lbo.putstr("lbo\nlbo");
-		System.out.print("print\n");
-		lbo.putstr("\n");
-	}
-}
-
-This example produces the output:

-

lbo
-print
-lbo
-
- -

The class BufferOutput implements a very simple buffered version of an OutputStream, flushing the output when the buffer is full or flush is invoked. The subclass LineBufferOutput declares only a constructor and a single method putchar, which overrides the method putchar of BufferOutput. It inherits the methods putstr and flush from class BufferOutput.

- -

In the putchar method of a LineBufferOutput object, if the character argument is a newline, then it invokes the flush method. The critical point about overriding in this example is that the method putstr, which is declared in class BufferOutput, invokes the putchar method defined by the current object this, which is not necessarily the putchar method declared in class BufferOutput.

- -

Thus, when putstr is invoked in main using the LineBufferOutput object lbo, the invocation of putchar in the body of the putstr method is an invocation of the putchar of the object lbo, the overriding declaration of putchar that checks for a newline. This allows a subclass of BufferOutput to change the behavior of the putstr method without redefining it.

- -

Documentation for a class such as BufferOutput, which is designed to be extended, should clearly indicate what is the contract between the class and its subclasses, and should clearly indicate that subclasses may override the putchar method in this way. The implementor of the BufferOutput class would not, therefore, want to change the implementation of putstr in a future implementation of BufferOutput not to use the method putchar, because this would break the preexisting contract with subclasses. See the further discussion of binary compatibility in §13, especially §13.2.

- - -

8.4.10.7 Example: Incorrect Overriding because of Throws

- -This example uses the usual and conventional form for declaring a new exception type, in its declaration of the class BadPointException:

-

class BadPointException extends Exception {
-	BadPointException() { super(); }
-	BadPointException(String s) { super(s); }
-}
-class Point {
-	int x, y;
-	void move(int dx, int dy) { x += dx; y += dy; }
-}
-class CheckedPoint extends Point {
-	void move(int dx, int dy) throws BadPointException {
-		if ((x + dx) < 0 || (y + dy) < 0)
-			throw new BadPointException();
-		x += dx; y += dy;
-	}
-}
-
-This example results in a compile-time error, because the override of method move in class CheckedPoint declares that it will throw a checked exception that the move in class Point has not declared. If this were not considered an error, an invoker of the method move on a reference of type Point could find the contract between it and Point broken if this exception were thrown.

- -

Removing the throws clause does not help:

-
class CheckedPoint extends Point {
-	void move(int dx, int dy) {
-		if ((x + dx) < 0 || (y + dy) < 0)
-			throw new BadPointException();
-		x += dx; y += dy;
-	}
-}
-
- -

A different compile-time error now occurs, because the body of the method move cannot throw a checked exception, namely BadPointException, that does not appear in the throws clause for move.

- - -

8.5 Member Type Declarations

- -A member class is a class whose declaration is directly enclosed in another class or interface declaration. Similarly, a member interface is an interface whose declaration is directly enclosed in another class or interface declaration. The scope (§6.3) of a member class or interface is specified in §8.1.6.

- -If the class declares a member type with a certain name, then the declaration of that type is said to hide any and all accessible declarations of member types with the same name in superclasses and superinterfaces of the class.

- -Within a class C, a declaration d of a member type named n shadows the declarations of any other types named n that are in scope at the point where d occurs.

- -If a member class or interface declared with simple name C is directly enclosed within the declaration of a class with fully qualified name N, then the member class or interface has the fully qualified name N.C. A class inherits from its direct superclass and direct superinterfaces all the non-private member types of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

- -A class may inherit two or more type declarations with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited class or interface by its simple name

- -If the same type declaration is inherited from an interface by multiple paths, the class or interface is considered to be inherited only once. It may be referred to by its simple name without ambiguity.

- - -

8.5.1 Modifiers

- -The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if a member type declaration has more than one of the access modifiers public, protected, and private.

- -Member type declarations may have annotation modifers just like any type or member declaration.

- - -

8.5.2 Static Member Type Declarations

- -The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.

- -It is a compile-time error if a static class contains a usage of a non-static member of an enclosing class.

- -Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier.

- - -

8.6 Instance Initializers

- -An instance initializer declared in a class is executed when an instance of the class is created (§15.9), as specified in §8.8.7.1.

-

-InstanceInitializer:
-	Block
-
-It is compile-time error if an instance initializer of a named class can throw a checked exception unless that exception or one of its supertypes is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor. An instance initializer in an anonymous class (§15.9.5) can throw any exceptions.

- -

- -

The rules above distinguish between instance initializers in named and anonymous classes. This distinction is deliberate. A given anonymous class is only instantiated at a single point in a program. It is therefore possible to directly propagate information about what exceptions might be raised by an anonymous class' instance initializer to the surrounding expression. Named classes, on the other hand, can be instantiated in many places. Therefore the only way to propagate information about what exceptions might be raised by an instance initializer of a named class is through the throws clauses of its constructors. It follows that a more liberal rule can be used in the case of anonymous classes. Similar comments apply to instance variable initializers.

- -It is a compile-time error if an instance initializer cannot complete normally (§14.21). If a return statement (§14.17) appears anywhere within an instance initializer, then a compile-time error occurs.

- -Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to instance variables.

- -Instance initializers are permitted to refer to the current object this (§15.8.3), to any type variables (§4.4) in scope and to use the keyword super (§15.11.2, §15.12).

- - -

8.7 Static Initializers

- -Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).

-

-StaticInitializer:
-	static Block
-
-It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.6) with a checked exception (§11.2). It is a compile-time error if a static initializer cannot complete normally (§14.21).

- -The static initializers and class variable initializers are executed in textual order.

- -Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to class variables.

- -If a return statement (§14.17) appears anywhere within a static initializer, then a compile-time error occurs.

- -If the keyword this (§15.8.3) or any type variable (§4.4) defined outside the initializer or the keyword super (§15.11, §15.12) appears anywhere within a static initializer, then a compile-time error occurs.

- - -

8.8 Constructor Declarations

- -A constructor is used in the creation of an object that is an instance of a class:

-

-ConstructorDeclaration:
-	ConstructorModifiersopt ConstructorDeclarator
-		Throwsopt ConstructorBody
-
-ConstructorDeclarator:
-	TypeParametersopt SimpleTypeName ( FormalParameterListopt )
-	
-
-The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration; otherwise a compile-time error occurs. In all other respects, the constructor declaration looks just like a method declaration that has no result type.

- -

- -

Here is a simple example:

-
class Point {
-	int x, y;
-	Point(int x, int y) { this.x = x; this.y = y; }
-}
-
-Constructors are invoked by class instance creation expressions (§15.9), by the conversions and concatenations caused by the string concatenation operator + (§15.18.1), and by explicit constructor invocations from other constructors (§8.8.7). Constructors are never invoked by method invocation expressions (§15.12).

- -Access to constructors is governed by access modifiers (§6.6).

- -

This is useful, for example, in preventing instantiation by declaring an inaccessible constructor (§8.8.10).

- -Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

- - -

8.8.1 Formal Parameters and Formal Type Parameter

- -The formal parameters and formal type parameters of a constructor are identical in structure and behavior to the formal parameters of a method (§8.4.1).

- - -

8.8.2 Constructor Signature

- -It is a compile-time error to declare two constructors with override-equivalent (§8.4.2) signatures in a class. It is a compile-time error to declare two constructors whose signature has the same erasure (§4.6) in a class.

- - -

8.8.3 Constructor Modifiers

-
-ConstructorModifiers:
-	ConstructorModifier
-	ConstructorModifiers ConstructorModifier
-
-ConstructorModifier: one of
-	 Annotation public protected private
-
-The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a constructor declaration, or if a constructor declaration has more than one of the access modifiers public, protected, and private.

- -If no access modifier is specified for the constructor of a normal class, the constructor has default access. If no access modifier is specified for the constructor of an enum type, the constructor is private. It is a compile-time error if the constructor of an enum type (§8.9) is declared public or protected.

- -If an annotation a on a constructor corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.CONSTRUCTOR, or a compile-time error occurs. Annotations are further discussed in §9.7.

- -

Unlike methods, a constructor cannot be abstract, static, final, native, strictfp, or synchronized. A constructor is not inherited, so there is no need to declare it final and an abstract constructor could never be implemented. A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static. There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work. The lack of native constructors is an arbitrary language design choice that makes it easy for an implementation of the Java virtual machine to verify that superclass constructors are always properly invoked during object creation.

- -

Note that a ConstructorModifier cannot be declared strictfp. This difference in the definitions for ConstructorModifier and MethodModifier (§8.4.3) is an intentional language design choice; it effectively ensures that a constructor is FP-strict (§15.4) if and only if its class is FP-strict.

- - -

8.8.4 Generic Constructors

- -It is possible for a constructor to be declared generic, independently of whether the class the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables (§4.4). These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, as described in §8.1.2.

- -The scope of a constructor's type parameter is the entire declaration of the constructor, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

- -Type parameters of generic constructor need not be provided explicitly when a generic constructor is invoked. When they are not provided, they are inferred as specified in §15.12.2.7.

- -

- - -

8.8.5 Constructor Throws

- -The throws clause for a constructor is identical in structure and behavior to the throws clause for a method (§8.4.6).

- - -

8.8.6 The Type of a Constructor

- -The type of a constructor consists of its signature and the exception types given its throws clause.

- - -

8.8.7 Constructor Body

- -The first statement of a constructor body may be an explicit invocation of another constructor of the same class or of the direct superclass (§8.8.7.1).

-

-ConstructorBody:
-	{ ExplicitConstructorInvocationopt BlockStatementsopt }
-
-It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this. If the constructor is a constructor for an enum type (§8.9), it is a compile-time error for it to invoke the superclass constructor explicitly.

- -If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

- -Except for the possibility of explicit constructor invocations, the body of a constructor is like the body of a method (§8.4.7). A return statement (§14.17) may be used in the body of a constructor if it does not include an expression.

- -

In the example:

-
class Point {
-	int x, y;
-	Point(int x, int y) { this.x = x; this.y = y; }
-}
-class ColoredPoint extends Point {
-	static final int WHITE = 0, BLACK = 1;
-	int color;
-	ColoredPoint(int x, int y) {
-		this(x, y, WHITE);
-	}
-	ColoredPoint(int x, int y, int color) {
-		super(x, y);
-		this.color = color;
-	}
-}
-
-the first constructor of ColoredPoint invokes the second, providing an additional argument; the second constructor of ColoredPoint invokes the constructor of its superclass Point, passing along the coordinates.

- -§12.5 and §15.9 describe the creation and initialization of new class instances.

- - -

8.8.7.1 Explicit Constructor Invocations

-
-ExplicitConstructorInvocation:
-	NonWildTypeArgumentsopt this ( ArgumentListopt ) ;
-	NonWildTypeArgumentsopt super ( ArgumentListopt ) ;
-	Primary. NonWildTypeArgumentsopt super ( ArgumentListopt ) ; 
-
-NonWildTypeArguments:
-	< ReferenceTypeList >
-
-ReferenceTypeList: 
-	ReferenceType
-	ReferenceTypeList , ReferenceType
-
-

- -Explicit constructor invocation statements can be divided into two kinds:

-

- -

Here is an example of a qualified superclass constructor invocation:

- -
class Outer {
-	class Inner{}
-}
-class ChildOfInner extends Outer.Inner {
-	ChildOfInner(){(new Outer()).super();}
-}
-
-An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

- -

For example, if the first constructor of ColoredPoint in the example above were changed to:

-
ColoredPoint(int x, int y) {
-	this(x, y, color);
-}
-
-then a compile-time error would occur, because an instance variable cannot be used within a superclass constructor invocation.

- -An explicit constructor invocation statement can throw an exception type E iff either:

-

-

- -If an anonymous class instance creation expression appears within an explicit constructor invocation statement, then the anonymous class may not refer to any of the enclosing instances of the class whose constructor is being invoked.

- -

For example:

-
class Top {
-	int x;
-	class Dummy {
-		Dummy(Object o) {}
-	}
-	class Inside extends Dummy {
-		Inside() {
-			super(new Object() { int r = x; }); // error
-		}		
-		Inside(final int y) {
-			super(new Object() { int r = y; }); // correct
-		}
-	}
-}
-
-Let C be the class being instantiated, let S be the direct superclass of C, and let i be the instance being created. The evaluation of an explicit constructor invocation proceeds as follows:

-

-

- - -

8.8.8 Constructor Overloading

- -Overloading of constructors is identical in behavior to overloading of methods. The overloading is resolved at compile time by each class instance creation expression (§15.9).

- - -

8.8.9 Default Constructor

- -If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:

-

-A compile-time error occurs if a default constructor is provided by the compiler but the superclass does not have an accessible constructor that takes no arguments.

- -A default constructor has no throws clause.

- -

It follows that if the nullary constructor of the superclass has a throws clause, then a compile-time error will occur.

- -In an enum type (§8.9), the default constructor is implicitly private. Otherwise, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

- -

Thus, the example:

-
public class Point {
-	int x, y;
-}
-
-is equivalent to the declaration:

-

public class Point {
-	int x, y;
-	public Point() { super(); }
-}
-
-where the default constructor is public because the class Point is public.

- -

The rule that the default constructor of a class has the same access modifier as the class itself is simple and intuitive. Note, however, that this does not imply that the constructor is accessible whenever the class is accessible. Consider

-
package p1;
-public class Outer {
- 	protected class Inner{}
-}
-
-package p2;
-class SonOfOuter extends p1.Outer {
-	void foo() {
- 		new Inner(); // compile-time access error
-	}
-}
-
-
-The constructor for Inner is protected. However, the constructor is protected relative to Inner, while Inner is protected relative to Outer. So, Inner is accessible in SonOfOuter, since it is a subclass of Outer. Inner's constructor is not accessible in SonOfOuter, because the class SonOfOuter is not a subclass of Inner! Hence, even though Inner is accessible, its default constructor is not.

- - -

8.8.10 Preventing Instantiation of a Class

- -A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, to prevent the creation of an implicit constructor, and declaring all constructors to be private. A public class can likewise prevent the creation of instances outside its package by declaring at least one constructor, to prevent creation of a default constructor with public access, and declaring no constructor that is public.

- -

Thus, in the example:

-
class ClassOnly {
-	private ClassOnly() { }
-	static String just = "only the lonely";
-}
-
-the class ClassOnly cannot be instantiated, while in the example:

-

package just;
-public class PackageOnly {
-	PackageOnly() { }
-	String[] justDesserts = { "cheesecake", "ice cream" };
-}
-
-the class PackageOnly can be instantiated only within the package just, in which it is declared.

- - -

8.9 Enums

- -An enum declaration has the form:

-

-
-EnumDeclaration:
-	ClassModifiersopt enum Identifier Interfacesopt EnumBody
-
-EnumBody:
-	{ EnumConstantsopt ,opt EnumBodyDeclarationsopt }
-
-The body of an enum type may contain enum constants. An enum constant defines an instance of the enum type. An enum type has no instances other than those defined by its enum constants.

-


- -

- Discussion -

- -

- It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

- -Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant. (The equals method in Enum is a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.)

-


- -

-

-
-EnumConstants:
-	EnumConstant
-	EnumConstants , EnumConstant
-
-EnumConstant:
-	Annotations Identifier Argumentsopt ClassBodyopt
-
-Arguments:
-	( ArgumentListopt )
-
-EnumBodyDeclarations:
-	; ClassBodyDeclarationsopt
-	
-
-An enum constant may be preceded by annotation (§9.7) modifiers. If an annotation a on an enum constant corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.FIELD, or a compile-time error occurs.

- -An enum constant may be followed by arguments, which are passed to the constructor of the enum type when the constant is created during class initialization as described later in this section. The constructor to be invoked is chosen using the normal overloading rules (§15.12.2). If the arguments are omitted, an empty argument list is assumed. If the enum type has no constructor declarations, a parameterless default constructor is provided (which matches the implicit empty argument list). This default constructor is private.

- -The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors.

- -


-

- Discussion -

-

- - Instance methods declared in these class bodies are may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type.

-


- -

- -Enum types (§8.9) must not be declared abstract; doing so will result in a compile-time error. It is a compile-time error for an enum type E to have an abstract method m as a member unless E has one or more enum constants, and all of E's enum constants have class bodies that provide concrete implementations of m. It is a compile-time error for the class body of an enum constant to declare an abstract method.

- -

- -An enum type is implicitly final unless it contains at least one enum constant that has a class body. In any case, it is a compile-time error to explicitly declare an enum type to be final.

- -Nested enum types are implicitly static. It is permissable to explicitly declare a nested enum type to be static.

- -


-

- Discussion -

-

- - This implies that it is impossible to define a local (§14.3) enum, or to define an enum in an inner class (§8.1.3).

-


- -

- -Any constructor or member declarations within an enum declaration apply to the enum type exactly as if they had been present in the class body of a normal class declaration unless explicitly stated otherwise.

- -The direct superclass of an enum type named E is Enum<E>. In addition to the members it inherits from Enum<E>, for each declared enum constant with the name n the enum type has an implicitly declared public static final field named n of type E. These fields are considered to be declared in the same order as the corresponding enum constants, before any static fields explicitly declared in the enum type. Each such field is initialized to the enum constant that corresponds to it. Each such field is also considered to be annotated by the same annotations as the corresponding enum constant. The enum constant is said to be created when the corresponding field is initialized.

- -It is a compile-time error for an enum to declare a finalizer. An instance of an enum may never be finalized.

- -In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

-


-/**
-
* Returns an array containing the constants of this enum 
-* type, in the order they're declared.  This method may be
-* used to iterate over the constants as follows:
-*
-*    for(E c : E.values())
-*        System.out.println(c);
-*
-* @return an array containing the constants of this enum 
-* type, in the order they're declared
-*/
-public static E[] values();
-
-/**
-* Returns the enum constant of this type with the specified
-* name.
-* The string must match exactly an identifier used to declare
-* an enum constant in this type.  (Extraneous whitespace 
-* characters are not permitted.)
-* 
-* @return the enum constant with the specified name
-* @throws IllegalArgumentException if this enum type has no
-* constant with the specified name
-*/
-public static E valueOf(String name);
-
-
-

-


-

-Discussion -

-

- - It follows that enum type declarations cannot contain fields that conflict with the enum constants, and cannot contain methods that conflict with the automatically generated methods (values() and valueOf(String)) or methods that override the final methods in Enum: (equals(Object), hashCode(), clone(), compareTo(Object), name(), ordinal(), and getDeclaringClass()).

-


- - -

- -It is a compile-time error to reference a static field of an enum type that is not a compile-time constant (§15.28) from constructors, instance initializer blocks, or instance variable initializer expressions of that type. It is a compile-time error for the constructors, instance initializer blocks, or instance variable initializer expressions of an enum constant e to refer to itself or to an enum constant of the same type that is declared to the right of e.

- -


-

-Discussion -

- -

- - Without this rule, apparently reasonable code would fail at run time due to the initialization circularity inherent in enum types. (A circularity exists in any class with a "self-typed" static field.) Here is an example of the sort of code that would fail:

-

enum Color {
-        RED, GREEN, BLUE;
-        static final Map<String,Color> colorMap = 
-		new HashMap<String,Color>();
-        Color() {
-            colorMap.put(toString(), this);
-        }
-    } 
-	
- - Static initialization of this enum type would throw a NullPointerException because the static variable colorMap is uninitialized when the constructors for the enum constants run. The restriction above ensures that such code won't compile.

- -

- -Note that the example can easily be refactored to work properly:

-

enum Color {
-        RED, GREEN, BLUE;
-        static final Map<String,Color> colorMap = 
-		new HashMap<String,Color>();
-        static {
-            for (Color c : Color.values())
-                colorMap.put(c.toString(), c);
-        }
-    } 
-	
- -

- The refactored version is clearly correct, as static initialization occurs top to bottom.

-


- -

-


- -

- Discussion -

-

- - Here is program with a nested enum declaration that uses an enhanced for loop to iterate over the constants in the enum:

-

-public class Example1 {
-    public enum Season { WINTER, SPRING, SUMMER, FALL }
-
-    public static void main(String[] args) {
-        for (Season s : Season.values())
-            System.out.println(s);
-    }
-}
-
-

- - Running this program produces the following output:

-

-WINTER
-SPRING
-SUMMER
-FALL
-
-

- - Here is a program illustrating the use of EnumSet to work with subranges:

-

-import java.util.*;
-
-public class Example2 {
-    enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
-}
-
-    public static void main(String[] args) {
-        System.out.print("Weekdays: ");
-        for (Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY))
-            System.out.print(d + " ");
-        System.out.println();
-    }
-}
-
- -

- - Running this program produces the following output:

-

-Weekdays: MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY
-
- - EnumSet contains a rich family of static factories, so this technique can be generalized to work non-contiguous subsets as well as subranges. At first glance, it might appear wasteful to generate an EnumSet for a single iteration, but they are so cheap that this is the recommended idiom for iteration over a subrange. Internally, an EnumSet is represented with a single long assuming the enum type has 64 or fewer elements.

- -Here is a slightly more complex enum declaration for an enum type with an explicit instance field and an accessor for this field. Each member has a different value in the field, and the values are passed in via a constructor. In this example, the field represents the value, in cents, of an American coin. Note, however, that their are no restrictions on the type or number of parameters that may be passed to an enum constructor.

-

public enum Coin {
-    PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
-
-    Coin(int value) { this.value = value; }
-
-    private final int value;
-
-    public int value() { return value; }
-}
-
- - Switch statements are useful for simulating the addition of a method to an enum type from outside the type. This example "adds" a color method to the Coin type, and prints a table of coins, their values, and their colors.

-

-public class CoinTest {
-    public static void main(String[] args) {
-        for (Coin c : Coin.values())
-            System.out.println(c + ":   	"+ c.value() +"¢ 	" + color(c));
-    }
-    private enum CoinColor { COPPER, NICKEL, SILVER }
-    private static CoinColor color(Coin c) {
-        switch(c) {
-          case PENNY:
-            return CoinColor.COPPER;
-          case NICKEL:
-            return CoinColor.NICKEL;
-          case DIME: case QUARTER:
-            return CoinColor.SILVER;
-          default:
-            throw new AssertionError("Unknown coin: " + c);
-        }
-    }
-}
-
- - Running the program prints:

-

-PENNY:          1¢      COPPER
-NICKEL:         5¢      NICKEL
-DIME:           10¢     SILVER
-QUARTER:        25¢     SILVER
-
- - - -

- - In the following example, a playing card class is built atop two simple enum types. Note that each enum type would be as long as the entire example in the absence of the enum facility:

-

-import java.util.*;
-public class Card implements Comparable<Card>, java.io.Serializable {
-    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,JACK, 
-QUEEN, KING, ACE }
-    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
-    private final Rank rank;
-    private final Suit suit;
-    private Card(Rank rank, Suit suit) {
-        if (rank == null || suit == null)
-            throw new NullPointerException(rank + ", " + suit);
-        this.rank = rank;
-        this.suit = suit;
-    }
-    public Rank rank() { return rank; }
-    public Suit suit() { return suit; }
-    public String toString() { return rank + " of " + suit; }
-    // Primary sort on suit, secondary sort on rank
-    public int compareTo(Card c) {
-        int suitCompare = suit.compareTo(c.suit);
-        return (suitCompare != 0 ? suitCompare : rank.compareTo(c.rank));
-    }
-    private static final List<Card> prototypeDeck = new ArrayList<Card>(52);
-    static {
-        for (Suit suit : Suit.values())
-            for (Rank rank : Rank.values())
-                prototypeDeck.add(new Card(rank, suit));
-    }
-    // Returns a new deck
-    public static List<Card> newDeck() {
-        return new ArrayList<Card>(prototypeDeck);
-    }
-}
-
- - Here's a little program that exercises the Card class. It takes two integer parameters on the command line, representing the number of hands to deal and the number of cards in each hand:

-

-import java.util.*;
-class Deal {
-    public static void main(String args[]) {
-		int numHands     = Integer.parseInt(args[0]);
-		int cardsPerHand = Integer.parseInt(args[1]);
-		List<Card> deck  = Card.newDeck();
-		Collections.shuffle(deck);
-		for (int i=0; i < numHands; i++)
-            System.out.println(dealHand(deck, cardsPerHand));
-    	}
-    /**
-	 * Returns a new ArrayList consisting of the last n elements of 
-	 * deck, which are removed from deck.  The returned list is
-	 * sorted using the elements' natural ordering.
-	*/
-    public static <E extends Comparable<E>> ArrayList<E>
-            dealHand(List<E> deck, int n) {
-        int deckSize = deck.size();
-        List<E> handView = deck.subList(deckSize - n, deckSize);
-        ArrayList<E> hand = new ArrayList<E>(handView);
-        handView.clear();
-        Collections.sort(hand);
-        return hand;
-    }
-}
-
- - Running the program produces results like this:

-

-java Deal 4 5
-[FOUR of SPADES, NINE of CLUBS, NINE of SPADES, QUEEN of SPADES, KING of SPADES]
-[THREE of DIAMONDS, FIVE of HEARTS, SIX of SPADES, SEVEN of DIAMONDS, KING of 
-DIAMONDS]
-[FOUR of DIAMONDS, FIVE of SPADES, JACK of CLUBS, ACE of DIAMONDS, ACE of 
-HEARTS]
-[THREE of HEARTS, FIVE of DIAMONDS, TEN of HEARTS, JACK of HEARTS, QUEEN of 
-HEARTS]
-
- - The next example demonstrates the use of constant-specific class bodies to attach behaviors to the constants. (It is anticipated that the need for this will be rare.):

-

-import java.util.*;
-public enum Operation {
-    PLUS {
-        double eval(double x, double y) { return x + y; }
-    },
-    MINUS {
-        double eval(double x, double y) { return x - y; }
-    },
-    TIMES {
-        double eval(double x, double y) { return x * y; }
-    },
-    DIVIDED_BY {
-        double eval(double x, double y) { return x / y; }
-    };
-    // Perform the arithmetic operation represented by this constant
-   // abstract double eval(double x, double y);
-    public static void main(String args[]) {
-        double x = Double.parseDouble(args[0]);
-        double y = Double.parseDouble(args[1]);
-
-        for (Operation op : Operation.values())
-            System.out.println(x + " " + op + " " + y + " = " + op.eval(x, y));
-    }
-}
-
- - Running this program produces the following output:

-

-java Operation 2.0 4.0
-2.0 PLUS 4.0 = 6.0
-2.0 MINUS 4.0 = -2.0
-2.0 TIMES 4.0 = 8.0
-2.0 DIVIDED_BY 4.0 = 0.5
-
- - The above pattern is suitable for moderately sophisticated programmers. It is admittedly a bit tricky, but it is much safer than using a case statement in the base type (Operation), as the pattern precludes the possibility of forgetting to add a behavior for a new constant (you'd get a compile-time error).

- -


-

- - - -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - Interfaces - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 9

- -

Interfaces

-

- -An interface declaration introduces a new reference type whose members are classes, interfaces, constants and abstract methods. This type has no implementation, but otherwise unrelated classes can implement it by providing implementations for its abstract methods.

- -A nested interface is any interface whose declaration occurs within the body of another class or interface. A top-level interface is an interface that is not a nested interface.

- -We distinguish between two kinds of interfaces - normal interfaces and annotation types.

- -This chapter discusses the common semantics of all interfaces-normal interfaces and annotation types (§9.6), top-level (§7.6) and nested (§8.5, §9.5). Details that are specific to particular kinds of interfaces are discussed in the sections dedicated to these constructs.

- -

Programs can use interfaces to make it unnecessary for related classes to share a common abstract superclass or to add methods to Object.

- -An interface may be declared to be a direct extension of one or more other interfaces, meaning that it implicitly specifies all the member types, abstract methods and constants of the interfaces it extends, except for any member types and constants that it may hide.

- -A class may be declared to directly implement one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do. This (multiple) interface inheritance allows objects to support (multiple) common behaviors without sharing any implementation.

- -A variable whose declared type is an interface type may have as its value a reference to any instance of a class which implements the specified interface. It is not sufficient that the class happen to implement all the abstract methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface.

- - -

9.1 Interface Declarations

- -An interface declaration specifies a new named reference type. There are two kinds of interface declarations - normal interface declarations and annotation type declarations:

- -InterfaceDeclaration: - NormalInterfaceDeclaration - AnnotationTypeDeclaration - - -

- -Annotation types are described further in §9.6.

-

-
-NormalInterfaceDeclaration:
-        InterfaceModifiersopt interface Identifier TypeParametersopt
-                ExtendsInterfacesopt InterfaceBody
-                
-
-The Identifier in an interface declaration specifies the name of the interface. A compile-time error occurs if an interface has the same simple name as any of its enclosing classes or interfaces.

- - -

9.1.1 Interface Modifiers

- -An interface declaration may include interface modifiers:

-

-
-InterfaceModifiers:
-        InterfaceModifier
-        InterfaceModifiers InterfaceModifier
-
-InterfaceModifier: one of
-         Annotation public protected private
-        abstract static strictfp
-
-The access modifier public is discussed in §6.6. Not all modifiers are applicable to all kinds of interface declarations. The access modifiers protected and private pertain only to member interfaces within a directly enclosing class declaration (§8.5) and are discussed in §8.5.1. The access modifier static pertains only to member interfaces (§8.5, §9.5). A compile-time error occurs if the same modifier appears more than once in an interface declaration. If an annotation a on an interface declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.TYPE, or a compile-time error occurs. Annotation modifiers are described further in §9.7.

- - -

9.1.1.1 abstract Interfaces

- -Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.

- - -

9.1.1.2 strictfp Interfaces

- -The effect of the strictfp modifier is to make all float or double expressions within the interface declaration be explicitly FP-strict (§15.4).

- -This implies that all nested types declared in the interface are implicitly strictfp.

- - -

9.1.2 Generic Interfaces and Type Parameters

- -An interface is generic if it declares one or more type variables (§4.4). These type variables are known as the type parameters of the interface. The type parameter section follows the interface name and is delimited by angle brackets. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.

- -The scope of an interface's type parameter is the entire declaration of the interface including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

- -It is a compile-time error to refer to a type parameter of an interface I anywhere in the declaration of a field or type member of I.

- - -

9.1.3 Superinterfaces and Subinterfaces

- -If an extends clause is provided, then the interface being declared extends each of the other named interfaces and therefore inherits the member types, methods, and constants of each of the other named interfaces. These other named interfaces are the direct superinterfaces of the interface being declared. Any class that implements the declared interface is also considered to implement all the interfaces that this interface extends.

-

-
-ExtendsInterfaces:
-        extends InterfaceType
-        ExtendsInterfaces , InterfaceType
-
-
-The following is repeated from §4.3 to make the presentation here clearer:

-

-
-InterfaceType:
-        TypeDeclSpecifier TypeArgumentsopt
-        
-
-Given a (possibly generic) interface declaration for I<F1,...,Fn>, n0, the direct superinterfaces of the interface type (§4.5) I<F1,...,Fn> are the types given in the extends clause of the declaration of I if an extends clause is present.

- -Let I<F1,...,Fn>, n>0, be a generic interface declaration. The direct superinterfaces of the parameterized interface type I<T1,...,Tn> , where Ti, 1in, is a type, are all types J<U1 theta , ..., Uk theta>, where J<U1,...,Uk> is a direct superinterface of I<F1,...,Fn>, and theta is the substitution [F1 := T1, ..., Fn := Tn].

- -Each InterfaceType in the extends clause of an interface declaration must name an accessible interface type; otherwise a compile-time error occurs.

- -An interface I directly depends on a type T if T is mentioned in the extends clause of I either as a superinterface or as a qualifier within a superinterface name. An interface I depends on a reference type T if any of the following conditions hold:

-

-A compile-time error occurs if an interface depends on itself.

- -While every class is an extension of class Object, there is no single interface of which all interfaces are extensions.

- -The superinterface relationship is the transitive closure of the direct superinterface relationship. An interface K is a superinterface of interface I if either of the following is true:

-

-Interface I is said to be a subinterface of interface K whenever K is a superinterface of I.

- - -

9.1.4 Interface Body and Member Declarations

- -The body of an interface may declare members of the interface:

-

-
-InterfaceBody:
-        { InterfaceMemberDeclarationsopt }
-
-InterfaceMemberDeclarations:
-        InterfaceMemberDeclaration
-        InterfaceMemberDeclarations InterfaceMemberDeclaration
-
-InterfaceMemberDeclaration:
-        ConstantDeclaration
-        AbstractMethodDeclaration
-        ClassDeclaration 
-        InterfaceDeclaration
-        ;                          
-
-The scope of the declaration of a member m declared in or inherited by an interface type I is the entire body of I, including any nested type declarations.

- - -

9.1.5 Access to Interface Member Names

- -All interface members are implicitly public. They are accessible outside the package where the interface is declared if the interface is also declared public or protected, in accordance with the rules of §6.6.

- - -

9.2 Interface Members

- -The members of an interface are:

-

-It follows that is a compile-time error if the interface declares a method with a signature that is override-equivalent (§8.4.2) to a public method of Object, but has a different return type or incompatible throws clause.

- -The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields, classes, and interfaces that it hides and methods that it overrides.

- - -

9.3 Field (Constant) Declarations

-
-
-ConstantDeclaration:
-        ConstantModifiersopt Type VariableDeclarators ;
-
-ConstantModifiers: 
-        ConstantModifier
-        ConstantModifier ConstantModifers 
-
-ConstantModifier: one of
-        Annotation public static final 
-
-Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

- -If an annotation a on a field declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.FIELD, or a compile-time error occurs. Annotation modifiers are described further in §9.7.

- -If the interface declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superinterfaces of the interface.

- -It is a compile-time error for the body of an interface declaration to declare two fields with the same name.

- -It is possible for an interface to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the interface to refer to either field by its simple name will result in a compile-time error, because such a reference is ambiguous.

- -There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.

- - -

9.3.1 Initialization of Fields in Interfaces

- -Every field in the body of an interface must have an initialization expression, which need not be a constant expression. The variable initializer is evaluated and the assignment performed exactly once, when the interface is initialized (§12.4).

- -A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface.

- -

Thus:

-
interface Test {
-        float f = j;
-        int j = 1;
-        int k = k+1;
-}
-
-causes two compile-time errors, because j is referred to in the initialization of f before j is declared and because the initialization of k refers to k itself.

- -

One subtlety here is that, at run time, fields that are initialized with compile-time constant values are initialized first. This applies also to static final fields in classes (§8.3.2.1). This means, in particular, that these fields will never be observed to have their default initial values (§4.12.5), even by devious programs. See §12.4.2 and §13.4.9 for more discussion.

- -If the keyword this (§15.8.3) or the keyword super (15.11.2, 15.12) occurs in an initialization expression for a field of an interface, then unless the occurrence is within the body of an anonymous class (§15.9.5), a compile-time error occurs.

- - -

9.3.2 Examples of Field Declarations

- -The following example illustrates some (possibly subtle) points about field declarations.

- - -

9.3.2.1 Ambiguous Inherited Fields

- -If two fields with the same name are inherited by an interface because, for example, two of its direct superinterfaces declare fields with that name, then a single ambiguous member results. Any use of this ambiguous member will result in a compile-time error.

- -

- -Thus in the example:

-

interface BaseColors {
-        int RED = 1, GREEN = 2, BLUE = 4;
-}
-interface RainbowColors extends BaseColors {
-        int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7;
-}
-interface PrintColors extends BaseColors {
-        int YELLOW = 8, CYAN = 16, MAGENTA = 32;
-}
-interface LotsOfColors extends RainbowColors, PrintColors {
-        int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90;
-}
-
-the interface LotsOfColors inherits two fields named YELLOW. This is all right as long as the interface does not contain any reference by simple name to the field YELLOW. (Such a reference could occur within a variable initializer for a field.)

- -

Even if interface PrintColors were to give the value 3 to YELLOW rather than the value 8, a reference to field YELLOW within interface LotsOfColors would still be considered ambiguous.

- - -

9.3.2.2 Multiply Inherited Fields

- -If a single field is inherited multiple times from the same interface because, for example, both this interface and one of this interface's direct superinterfaces extend the interface that declares the field, then only a single member results. This situation does not in itself cause a compile-time error.

- -

In the example in the previous section, the fields RED, GREEN, and BLUE are inherited by interface LotsOfColors in more than one way, through interface RainbowColors and also through interface PrintColors, but the reference to field RED in interface LotsOfColors is not considered ambiguous because only one actual declaration of the field RED is involved.

- - -

9.4 Abstract Method Declarations

-
-
-AbstractMethodDeclaration:
-        AbstractMethodModifiersopt TypeParametersopt ResultType 
-MethodDeclarator Throwsopt ;
-
-AbstractMethodModifiers:
-        AbstractMethodModifier
-        AbstractMethodModifiers AbstractMethodModifier
-
-AbstractMethodModifier: one of
-        Annotation public abstract 
-
-The access modifier public is discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in an abstract method declaration.

- -Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.

- -Every method declaration in the body of an interface is implicitly public.

- -

For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

- -

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

- -Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.

- -Note that a method declared in an interface must not be declared strictfp or native or synchronized, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties. However, a method declared in an interface may be implemented by a method that is declared strictfp or native or synchronized in a class that implements the interface.

- -If an annotation a on a method declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.METHOD, or a compile-time error occurs. Annotation modifiers are described further in §9.7.

- -It is a compile-time error for the body of an interface to declare, explicitly or implicitly, two methods with override-equivalent signatures (§8.4.2). However, an interface may inherit several methods with such signatures (§9.4.1).

- -Note that a method declared in an interface must not be declared final or a compile-time error occurs. However, a method declared in an interface may be implemented by a method that is declared final in a class that implements the interface.

- -A method in an interface may be generic. The rules for formal type parameters of a generic method in an interface are the same as for a generic method in a class (§8.4.4).

- - -

9.4.1 Inheritance and Overriding

- -An instance method m1 declared in an interface I overrides another instance method, m2, declared in interface J iff both of the following are true:

-

    - -
  1. I is a subinterface of J. - -
  2. The signature of m1 is a subsignature (§8.4.2) of the signature of m2. -
- -If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type-substitutable (§8.4.5) for d2, or a compile-time error occurs. Furthermore, if R1 is not a subtype of R2, an unchecked warning must be issued.

- -Moreover, a method declaration must not have a throws clause that conflicts (§8.4.6) with that of any method that it overrides; otherwise, a compile-time error occurs.

- -It is a compile time error if a type declaration T has a member method m1 and there exists a method m2 declared in T or a supertype of T such that all of the following conditions hold:

-

-

- -Methods are overridden on a signature-by-signature basis. If, for example, an interface declares two public methods with the same name, and a subinterface overrides one of them, the subinterface still inherits the other method.

- -An interface inherits from its direct superinterfaces all methods of the superinterfaces that are not overridden by a declaration in the interface.

- -It is possible for an interface to inherit several methods with override-equivalent signatures (§8.4.2). Such a situation does not in itself cause a compile-time error. The interface is considered to inherit all the methods. However, one of the inherited methods must must be return type substitutable for any other inherited method; otherwise, a compile-time error occurs (The throws clauses do not cause errors in this case.)

- -There might be several paths by which the same method declaration is inherited from an interface. This fact causes no difficulty and never of itself results in a compile-time error.

- - -

9.4.2 Overloading

- -If two methods of an interface (whether both declared in the same interface, or both inherited by an interface, or one declared and one inherited) have the same name but different signatures that are not override-equivalent (§8.4.2), then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures that are not override-equivalent.

- - -

9.4.3 Examples of Abstract Method Declarations

- -The following examples illustrate some (possibly subtle) points about abstract method declarations.

- - -

9.4.3.1 Example: Overriding

- -Methods declared in interfaces are abstract and thus contain no implementation. About all that can be accomplished by an overriding method declaration, other than to affirm a method signature, is to refine the return type or to restrict the exceptions that might be thrown by an implementation of the method. Here is a variation of the example shown in (§8.4.3.1):

-

class BufferEmpty extends Exception {
-        BufferEmpty() { super(); }
-        BufferEmpty(String s) { super(s); }
-}
-class BufferException extends Exception {
-        BufferException() { super(); }
-        BufferException(String s) { super(s); }
-} 
-public interface Buffer {
-        char get() throws BufferEmpty, BufferException;
-}
-public interface InfiniteBuffer extends Buffer {
-         char get() throws BufferException;                                                                                             // override
-}
-
- -

9.4.3.2 Example: Overloading

- -In the example code:

-

interface PointInterface {
-        void move(int dx, int dy);
-}
-interface RealPointInterface extends PointInterface {
-        void move(float dx, float dy);
-        void move(double dx, double dy);
-}
-
-the method name move is overloaded in interface RealPointInterface with three different signatures, two of them declared and one inherited. Any non-abstract class that implements interface RealPointInterface must provide implementations of all three method signatures.

- - -

9.5 Member Type Declarations

- -Interfaces may contain member type declarations (§8.5). A member type declaration in an interface is implicitly static and public.

- -If a member type declared with simple name C is directly enclosed within the declaration of an interface with fully qualified name N, then the member type has the fully qualified name N.C.

- -If the interface declares a member type with a certain name, then the declaration of that field is said to hide any and all accessible declarations of member types with the same name in superinterfaces of the interface.

- -An interface inherits from its direct superinterfaces all the non-private member types of the superinterfaces that are both accessible to code in the interface and not hidden by a declaration in the interface.

- -An interface may inherit two or more type declarations with the same name. A compile-time error occurs on any attempt to refer to any ambiguously inherited class or interface by its simple name. If the same type declaration is inherited from an interface by multiple paths, the class or interface is considered to be inherited only once; it may be referred to by its simple name without ambiguity.

- - -

9.6 Annotation Types

- -An annotation type declaration is a special kind of interface declaration. To distinguish an annotation type declaration from an ordinary interface declaration, the keyword interface is preceded by an at sign (@).

-


- -

-Discussion -

- - - -

- - Note that the at sign (@) and the keyword interface are two distinct tokens; technically it is possible to separate them with whitespace, but this is strongly discouraged as a matter of style.

-


- -

-

-
-    AnnotationTypeDeclaration:
-        InterfaceModifiersopt @ interface Identifier AnnotationTypeBody
-
-    AnnotationTypeBody:
-        { AnnotationTypeElementDeclarationsopt }
-
-    AnnotationTypeElementDeclarations:
-        AnnotationTypeElementDeclaration
-        AnnotationTypeElementDeclarations AnnotationTypeElementDeclaration
-
-    AnnotationTypeElementDeclaration:
-        AbstractMethodModifiersopt Type Identifier ( ) DefaultValueopt ;
-        ConstantDeclaration
-        ClassDeclaration
-        InterfaceDeclaration
-        EnumDeclaration
-        AnnotationTypeDeclaration
-        ;
-
-    DefaultValue:
-        default ElementValue
-        
-        
- -

- -


-

-Discussion -

-

- The following restrictions are imposed on annotation type declarations by virtue of their context free syntax:

-

-
-

- -Unless explicitly modified herein, all of the rules that apply to ordinary interface declarations apply to annotation type declarations.

-


-

-Discussion -

- -

- - - For example, annotation types share the same namespace as ordinary class and interface types.

- -Annotation type declarations are legal wherever interface declarations are legal, and have the same scope and accessibility.

-


- -

- - -The Identifier in an annotation type declaration specifies the name of the annotation type. A compile-time error occurs if an annotation type has the same simple name as any of its enclosing classes or interfaces.

- -If an annotation a on an annotation type declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have either an element whose value is annotation.ElementType.ANNOTATION_TYPE, or an element whose value is annotation.ElementType.TYPE, or a compile-time error occurs.

-


-

-Discussion -

- -

- - - By convention, no AbstractMethodModifiers should be present except for annotations.

-


- -

- -The direct superinterface of an annotation type is always annotation.Annotation.

- -


-

- Discussion -

-

- - A consequence of the fact that an annotation type cannot explicitly declare a superclass or superinterface is that a subclass or subinterface of an annotation type is never itself an annotation type. Similarly, annotation.Annotation is not itself an annotation type.

-


- -

- -It is a compile-time error if the return type of a method declared in an annotation type is any type other than one of the following: one of the primitive types, String, Class and any invocation of Class, an enum type (§8.9), an annotation type, or an array (§10) of one of the preceding types. It is also a compile-time error if any method declared in an annotation type has a signature that is override-equivalent to that of any public or protected method declared in class Object or in the interface annotation.Annotation.

- -


-

- Discussion -

-

- - Note that this does not conflict with the prohibition on generic methods, as wildcards eliminate the need for an explicit type parameter.

-


- -

- -Each method declaration in an annotation type declaration defines an element of the annotation type. Annotation types can have zero or more elements. An annotation type has no elements other than those defined by the methods it explicitly declares.

- -


-

- Discussion -

-

- - Thus, an annotation type declaration inherits several members from annotation.Annotation, including the implicitly declared methods corresponding to the instance methods in Object, yet these methods do not define elements of the annotation type and it is illegal to use them in annotations.

- -Without this rule, we could not ensure that the elements were of the types representable in annotations, or that access methods for them would be available.

-


- -

- -It is a compile-time error if an annotation type T contains an element of type T, either directly or indirectly.

-


- -

- Discussion -

-

- - For example, this is illegal:

-

// Illegal self-reference!!
-@interface SelfRef {
-    SelfRef value();
-}
-
-and so is this:

-

// Illegal circularity!!
-@interface Ping {
-    Pong value();
-}
-@interface Pong {
-    Ping value();
-}
-
- - Note also that this specification precludes elements whose types are nested arrays. For example, this annotation type declaration is illegal:

-

-// Illegal nested array!!
-@interface Verboten {
-    String[][] value();
-}
-
- -

-


-

- -An annotation type element may have a default value specified for it. This is done by following its (empty) parameter list with the keyword default and the default value of the element.

- -Defaults are applied dynamically at the time annotations are read; default values are not compiled into annotations. Thus, changing a default value affects annotations even in classes that were compiled before the change was made (presuming these annotations lack an explicit value for the defaulted element).

- -An ElementValue is used to specify a default value. It is a compile-time error if the type of the element is not commensurate (§9.7) with the default value specified. An ElementValue is always FP-strict (§15.4).

- -


-

- Discussion -

-

- -The following annotation type declaration defines an annotation type with several elements:

-

// Normal annotation type declaration with several elements
-
-/**
-        * Describes the "request-for-enhancement" (RFE) 
-        * that led to the presence of 
-        * the annotated API element.
- */
-public @interface RequestForEnhancement {
-    int    id();        // Unique ID number associated with RFE
-    String synopsis();  // Synopsis of RFE
-    String engineer();  // Name of engineer who implemented RFE
-    String date();      // Date RFE was implemented
-}
-
-The following annotation type declaration defines an annotation type with no elements, termed a marker annotation type:

-

// Marker annotation type declaration
-
-/**
- * Annotation with this type indicates that the specification of the
- * annotated API element is preliminary and subject to change.
- */
-public @interface Preliminary { }
-
-
-
-

-By convention, the name of the sole element in a single-element annotation type is value.

- -


-

- Discussion -

-

- - Linguistic support for this convention is provided by the single element annotation construct (§9.7); one must obey the convention in order to take advantage of the construct.

-


- -

- -


-

- Discussion -

-

- - The convention is illustrated in the following annotation type declaration:

-

// Single-element annotation type declaration
-
-/**
- * Associates a copyright notice with the annotated API element.
- */
-public @interface Copyright {
-    String value();
-}
-
- - The following annotation type declaration defines a single-element annotation type whose sole element has an array type:

-

-// Single-element annotation type declaration with array-typed 
-// element
-
-/**
- * Associates a list of endorsers with the annotated class.
- */
-public @interface Endorsers {
-    String[] value();
-}
-
- - Here is an example of complex annotation types, annotation types that contain one or more elements whose types are also annotation types.

-

-// Complex Annotation Type
-
-/**
- * A person's name.  This annotation type is not designed to be used
- * directly to annotate program elements, but to define elements
- * of other annotation types.
- */
-public @interface Name {
-    String first();
-    String last();
-}
-
-/**
- * Indicates the author of the annotated program element.
- */
-public @interface Author {
-    Name value();
-}
-
-/**
- * Indicates the reviewer of the annotated program element.
- */
-public @interface Reviewer {
-    Name value();
-}
-
- - The following annotation type declaration provides default values for two of its four elements:

-

-// Annotation type declaration with defaults on some elements
-public @interface RequestForEnhancement {
-    int    id();       // No default - must be specified in 
-                                                        // each annotation
-    String synopsis(); // No default - must be specified in 
-                                                        // each annotation
-    String engineer()  default "[unassigned]";
-    String date()      default "[unimplemented]";
-}
-
- - The following annotation type declaration shows a Class annotation whose value is restricted by a bounded wildcard.

-

-// Annotation type declaration with bounded wildcard to 
-//      restrict Class annotation
-// The annotation type declaration below presumes the existence 
-// of this interface, which describes a formatter for Java 
-// programming language source code
-public interface Formatter { ... }
-
-// Designates a formatter to pretty-print the annotated class.
-public @interface PrettyPrinter {
-    Class<? extends Formatter> value();
-}
-
- - Note that the grammar for annotation type declarations permits other element declarations besides method declarations. For example, one might choose to declare a nested enum for use in conjunction with an annotation type:

-

-// Annotation type declaration with nested enum type declaration
-public @interface Quality {
-    enum Level { BAD, INDIFFERENT, GOOD }
-
-    Level value();
-}
-
-
-
-

- -

9.6.1 Predefined Annotation Types

- -Several annotation types are predefined in the libraries of the Java platform. Some of these predefined annotation types have special semantics. These semantics are specified in this section. This section does not provide a complete specification for the predefined annotations contained here in; that is the role of the appropriate API specifications. Only those semantics that require special behavior on the part of the Java compiler or virtual machine are specified here.

- - -

9.6.1.1 Target

- -The annotation type annotation.Target is intended to be used in meta-annotations that indicate the kind of program element that an annotation type is applicable to. Target has one element, of type annotation.ElementType[]. It is a compile-time error if a given enum constant appears more than once in an annotation whose corresponding type is annotation.Target. See sections §7.4.1, §8.1.1, §8.3.1, §8.4.1, §8.4.3, §8.8.3, §8.9, §9.1.1, §9.3, §9.4, §9.6 and §14.4 for the other effects of @annotation.Target annotations.

- - -

9.6.1.2 Retention

- -Annotations may be present only in the source code, or they may be present in the binary form of a class or interface. An annotation that is present in the binary may or may not be available at run-time via the reflective libraries of the Java platform.

- -The annotation type annotation.Retention is used to choose among the above possibilities. If an annotation a corresponds to a type T, and T has a (meta-)annotation m that corresponds to annotation.Retention, then:

-

-If T does not have a (meta-)annotation m that corresponds to annotation.Retention, then a Java compiler must treat T as if it does have such a meta-annotation m with an element whose value is annotation.RetentionPolicy.CLASS.

-


- -

- Discussion -

-

- - If m has an element whose value is annotation.RetentionPolicy.RUNTIME, the reflective libraries of the Java platform will make a available at run-time as well.

-


- -

- - -

9.6.1.3 Inherited

- -The annotation type annotation.Inherited is used to indicate that annotations on a class C corresponding to a given annotation type are inherited by subclasses of C.

- - -

9.6.1.4 Override

- -Programmers occasionally overload a method declaration when they mean to override it.

-


- -

- Discussion -

-

- - The classic example concerns the equals method. Programmers write the following:

-

    public boolean equals(Foo that) { ... }
-
-when they mean to write:

-

    public boolean equals(Object that) { ... }
-
-This is perfectly legal, but class Foo inherits the equals implementation from Object, which can cause some very subtle bugs.

-


- -

- -The annotation type Override supports early detection of such problems. If a method declaration is annotated with the annotation @Override, but the method does not in fact override any method declared in a superclass, a compile-time error will occur.

-


- -

- Discussion -

-

- - Note that if a method overrides a method from a superinterface but not from a superclass, using @Override will cause a compile-time error.

- -The rationale for this is that a concrete class that implements an interface will necessarily override all the interface's methods irrespective of the @Override annotation, and so it would be confusing to have the semantics of this annotation interact with the rules for implementing interfaces.

- -A by product of this rule is that it is never possible to use the @Override annotation in an interface declaration.

-


- -

- -

- - -

9.6.1.5 SuppressWarnings

- -The annotation type SuppressWarnings supports programmer control over warnings otherwise issued by the Java compiler. It contains a single element that is an array of String. If a program declaration is annotated with the annotation @SuppressWarnings(value = {S1, ... , Sk}), then a Java compiler must not report any warning identified by one of S1, ... , Sk if that warning would have been generated as a result of the annotated declaration or any of its parts.

- -Unchecked warnings are identified by the string "unchecked".

- -


-

- Discussion -

-

- - Recent Java compilers issue more warnings than previous ones did, and these "lint-like" warnings are very useful. It is likely that more such warnings will be added over time. To encourage their use, there should be some way to disable a warning in a particular part of the program when the programmer knows that the warning is inappropriate.

-


- -

-


- -

- Discussion -

-

- - Compiler vendors should document the warning names they support in conjunction with this annotation type. They are encouraged to cooperate to ensure that the same names work across multiple compilers.

-


- -

- - -

9.6.1.6 Deprecated

- -A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. A Java compiler must produce a warning when a deprecated type, method, field, or constructor is used (overridden, invoked, or referenced by name) unless:

-

-Use of the annotation @Deprecated on a local variable declaration or on a parameter declaration has no effect.

- - -

9.7 Annotations

- -An annotation is a modifier consisting of the name of an annotation type (§9.6) and zero or more element-value pairs, each of which associates a value with a different element of the annotation type. The purpose of an annotation is simply to associate information with the annotated program element.

- -Annotations must contain an element-value pair for every element of the corresponding annotation type, except for those elements with default values, or a compile-time error occurs. Annotations may, but are not required to, contain element-value pairs for elements with default values.

- -Annotations may be used as modifiers in any declaration, whether package (§7.4), class (§8), interface, field (§8.3, §9.3), method (§8.4, §9.4), parameter, constructor (§8.8), or local variable (§14.4).

-


- -

- Discussion -

-

- - Note that classes include enums (§8.9), and interfaces include annotation types (§9.6)

-


- -

- -Annotations may also be used on enum constants. Such annotations are placed immediately before the enum constant they annotate.

- -It is a compile-time error if a declaration is annotated with more than one annotation for a given annotation type.

-


- -

- Discussion -

-

- - Annotations are conventionally placed before all other modifiers, but this is not a requirement; they may be freely intermixed with other modifiers.

-


- -

- -There are three kinds of annotations. The first (normal annotation) is fully general. The others (marker annotation and single-element annotation) are merely shorthands.

-

-
-Annotations:
-        Annotation
-        Annotations Annotation
-
-    Annotation:
-        NormalAnnotation
-        MarkerAnnotation
-        SingleElementAnnotation
-        
-
-A normal annotation is used to annotate a program element:

-

-    NormalAnnotation:
-        @ TypeName ( ElementValuePairsopt )
-
-    ElementValuePairs:
-        ElementValuePair
-        ElementValuePairs , ElementValuePair
-
-    ElementValuePair:
-        Identifier = ElementValue
-
-    ElementValue:
-        ConditionalExpression
-        Annotation
-        ElementValueArrayInitializer
-
-    ElementValueArrayInitializer:
-        { ElementValuesopt ,opt }
-
-    ElementValues:
-        ElementValue
-        ElementValues , ElementValue
-        
-        
- -

-


-

- Discussion -

-

- - Note that the at-sign (@) is a token unto itself. Technically it is possible to put whitespace in between the at-sign and the TypeName, but this is discouraged.

-


- -

- -TypeName names the annotation type corresponding to the annotation. It is a compile-time error if TypeName does not name an annotation type. The annotation type named by an annotation must be accessible (§6.6) at the point where the annotation is used, or a compile-time error occurs.

- -The Identifier in an ElementValuePair must be the simple name of one of the elements of the annotation type identified by TypeName in the containing annotation. Otherwise, a compile-time error occurs. (In other words, the identifier in an element-value pair must also be a method name in the interface identified by TypeName.)

- -The return type of this method defines the element type of the element-value pair. An ElementValueArrayInitializer is similar to a normal array initializer (§10.6), except that annotations are permitted in place of expressions.

- -An element type T is commensurate with an element value V if and only if one of the following conditions is true:

-

-It is a compile-time error if the element type is not commensurate with the ElementValue.

- -If the element type is not an annotation type or an array type, ElementValue must be a ConditionalExpression (§15.25).

- -


-

- Discussion -

-

- - Note that null is not a legal element value for any element type.

-


- -

- -If the element type is an array type and the corresponding ElementValue is not an ElementValueArrayInitializer, an array value whose sole element is the value represented by the ElementValue is associated with the element. Otherwise, the value represented by ElementValue is associated with the element.

- -


-

- Discussion -

-

- - In other words, it is permissible to omit the curly braces when a single-element array is to be associated with an array-valued annotation type element.

- -Note that the array's element type cannot be an array type, that is, nested array types are not permitted as element types. (While the annotation syntax would permit this, the annotation type declaration syntax would not.)

-


- -

- -An annotation on an annotation type declaration is known as a meta-annotation. An annotation type may be used to annotate its own declaration. More generally, circularities in the transitive closure of the "annotates" relation are permitted. For example, it is legal to annotate an annotation type declaration with another annotation type, and to annotate the latter type's declaration with the former type. (The pre-defined meta-annotation types contain several such circularities.)

- -


-

- Discussion -

-

- - Here is an example of a normal annotation:

-

// Normal annotation
-@RequestForEnhancement(
-    id       = 2868724,
-    synopsis = "Provide time-travel functionality",
-    engineer = "Mr. Peabody",
-    date     = "4/1/2004"
-)
-public static void travelThroughTime(Date destination) { ... }
-
-

- -Note that the types of the annotations in the examples in this section are the annotation types defined in the examples in §9.6. Note also that the elements are in the above annotation are in the same order as in the corresponding annotation type declaration. This is not required, but unless specific circumstances dictate otherwise, it is a reasonable convention to follow.

-


- -

- -The second form of annotation, marker annotation, is a shorthand designed for use with marker annotation types:

-

-
-    MarkerAnnotation:
-        @ TypeName
-        
-
-It is simply a shorthand for the normal annotation:

-

        @TypeName()
-
- -

-


-

- Discussion -

-

- - Example:

-

-// Marker annotation
-@Preliminary public class TimeTravel { ... }
-
-

- -Note that it is legal to use marker annotations for annotation types with elements, so long as all the elements have default values.

-


- -

- -The third form of annotation, single-element annotation, is a shorthand designed for use with single-element annotation types:

-

-
-    SingleElementAnnotation:
-        @ TypeName ( ElementValue )
-
-
-It is shorthand for the normal annotation:

-

@TypeName ( value = ElementValue )
-
- -

-


-

- Discussion -

-

- - Example:

-

-// Single-element annotation
-@Copyright("2002 Yoyodyne Propulsion Systems, Inc., All rights reserved.")
-public class OscillationOverthruster { ... }
-
- - Example with array-valued single-element annotation:

-

-// Array-valued single-element annotation
-@Endorsers({"Children", "Unscrupulous dentists"})
-public class Lollipop { ... }
-
- - Example with single-element array-valued single-element annotation (note that the curly braces are omitted):

-

-// Single-element array-valued single-element annotation
-@Endorsers("Epicurus")
-public class Pleasure { ... }
-
- - Example with complex annotation:

-

-// Single-element complex annotation
-@Author(@Name(first = "Joe", last = "Hacker"))
-public class BitTwiddle { ... }
-
- -

- Note that it is legal to use single-element annotations for annotation types with multiple elements, so long as one element is named value, and all other elements have default values.

- -Here is an example of an annotation that takes advantage of default values:

- -

// Normal annotation with default values
-@RequestForEnhancement(
-    id       = 4561414,
-    synopsis = "Balance the federal budget"
-)
-public static void balanceFederalBudget() {
-    throw new UnsupportedOperationException("Not implemented");
-}
-
- - Here is an example of an annotation with a Class element whose value is restricted by the use of a bounded wildcard.

-

-// Single-element annotation with Class element restricted by bounded wildcard
-// The annotation presumes the existence of this class.
-class GorgeousFormatter implements Formatter { ... }
-@PrettyPrinter(GorgeousFormatter.class) public class Petunia {...}
-// This annotation is illegal, as String is not a subtype of Formatter!!
-@PrettyPrinter(String.class) public class Begonia { ... }
-
- - Here is an example of an annotation using an enum type defined inside the annotation type:

-

-// Annotation using enum type declared inside the annotation type
-@Quality(Quality.Level.GOOD)
-public class Karma {
-   ...
-}
-
- -
-

- -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - - Arrays - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 10

- -

Arrays

-

- -In the Java programming language arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

- -An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n-1, inclusive.

- -All the components of an array have the same type, called the component type of the array. If the component type of an array is T, then the type of the array itself is written T[].

- -The value of an array component of type float is always an element of the float value set (§4.2.3); similarly, the value of an array component of type double is always an element of the double value set. It is not permitted for the value of an array component of type float to be an element of the float-extended-exponent value set that is not also an element of the float value set, nor for the value of an array component of type double to be an element of the double-extended-exponent value set that is not also an element of the double value set.

- -The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the element type of the original array, and the components at this level of the data structure are called the elements of the original array.

- -

There are some situations in which an element of an array can be an array: if the element type is Object or Cloneable or java.io.Serializable, then some or all of the elements may be arrays, because any array object can be assigned to any variable of these types.

- - -

10.1 Array Types

- -An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. The number of bracket pairs indicates the depth of array nesting. An array's length is not part of its type.

- -The element type of an array may be any type, whether primitive or reference. In particular:

-

-Array types are used in declarations and in cast expressions (§15.16).

- - -

10.2 Array Variables

- -A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array. However, the initializer part of a declarator (§8.3) may create an array, a reference to which then becomes the initial value of the variable.

- -Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.

- -

Here are examples of declarations of array variables that do not create arrays:

-
int[] ai;			// array of int
-short[][] as;			// array of array of short
-Object[]	ao,		// array of Object
-		otherAo;	// array of Object
-Collection<?>[] ca;		// array of Collection of unknown type
-short		s,		// scalar short 
-		aas[][];	// array of array of short
-
-Here are some examples of declarations of array variables that create array objects:

-

Exception ae[] = new Exception[3]; 
-Object aao[][] = new Exception[2][3];
-int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
-char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
-				 'S', 't', 'r', 'i', 'n', 'g' }; 
-String[] aas = { "array", "of", "String", };
-
-

-The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

-

byte[] rowvector, colvector, matrix[];
-
-This declaration is equivalent to:

-

byte rowvector[], colvector[], matrix[][];
-
-Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

- -If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A. This may result in a run-time exception on a later assignment; see §10.10 for a discussion.

- - -

10.3 Array Creation

- -An array is created by an array creation expression (§15.10) or an array initializer (§10.6).

- -An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable length. It is a compile-time error if the element type is not a reifiable type (§4.7)

- -An array initializer creates an array and provides initial values for all its components.

- - -

10.4 Array Access

- -A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i]. All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.

- -Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§) and become int values. An attempt to access an array component with a long index value results in a compile-time error.

- -All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.

- - -

10.5 Arrays: A Simple Example

- -The example:

-

class Gauss {
-	public static void main(String[] args) {
-		int[] ia = new int[101];
-		for (int i = 0; i < ia.length; i++)
-			ia[i] = i;
-		int sum = 0;
-		for (int e : ia)
-			sum += e;
-		System.out.println(sum);
-	}
-}
-
-that produces the output:

-

5050
-
-declares a variable ia that has type array of int, that is, int[]. The variable ia is initialized to reference a newly created array object, created by an array creation expression (§15.10). The array creation expression specifies that the array should have 101 components. The length of the array is available using the field length, as shown.

- -

The example program fills the array with the integers from 0 to 100, sums these integers, and prints the result.

- - -

10.6 Array Initializers

- -An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values:

-

-
-ArrayInitializer:
-	{ VariableInitializersopt ,opt }
-
-VariableInitializers:
-	VariableInitializer
-	VariableInitializers , VariableInitializer
-	
-
-The following is repeated from §8.3 to make the presentation here clearer:

-

-
-VariableInitializer:
-	Expression
-	ArrayInitializer
-	
-
-An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".

- -The length of the constructed array will equal the number of expressions.

- -The expressions in an array initializer are executed from left to right in the textual order they occur in the source code. The nth variable initializer specifies the value of the n-1st array component. Each expression must be assignment-compatible (§5.2) with the array's component type, or a compile-time error results. It is a compile-time error if the component type of the array being initialized is not reifiable (§4.7).

- -If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.

- -A trailing comma may appear after the last expression in an array initializer and is ignored.

- -

As an example:

-
class Test {
-	public static void main(String[] args) {
-		int ia[][] = { {1, 2}, null };
-		for (int[] ea : ia)
-			for (int e: ea)
-				System.out.println(e);
-	}
-}
-
-prints:

-

1
-2
-
-before causing a NullPointerException in trying to index the second component of the array ia, which is a null reference.

- - -

10.7 Array Members

- -The members of an array type are all of the following:

-

-

- -An array thus has the same public fields and methods as the following class:

-

class A<T> implements Cloneable, java.io.Serializable {
-	public final int length = X;
-	public T[] clone() {
-		try {
-			return (T[])super.clone(); // unchecked warning
-		} catch (CloneNotSupportedException e) {
-			throw new InternalError(e.getMessage());
-		}
-	}
-}
-
-Note that the cast in the example above would generate an unchecked warning (§5.1.9) if arrays were really implemented this way.

- -Every array implements the interfaces Cloneable and java.io.Serializable.

- -

That arrays are cloneable is shown by the test program:

-
class Test {
-	public static void main(String[] args) {
-		int ia1[] = { 1, 2 };
-		int ia2[] = ia1.clone();
-		System.out.print((ia1 == ia2) + " ");
-		ia1[1]++;
-		System.out.println(ia2[1]);
-	}
-}
-
-which prints:

-

false 2
-
-showing that the components of the arrays referenced by ia1 and ia2 are different variables. (In some early implementations of the Java programming language this example failed to compile because the compiler incorrectly believed that the clone method for an array could throw a CloneNotSupportedException.)

- -A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

- -

This is shown by the example program:

-
class Test {
-	public static void main(String[] args) throws Throwable {
-		int ia[][] = { { 1 , 2}, null };
-		int ja[][] = ia.clone();
-		System.out.print((ia == ja) + " ");
-		System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
-	}
-}
-
-which prints:

-

false true
-
-showing that the int[] array that is ia[0] and the int[] array that is ja[0] are the same array.

- - -

10.8 Class Objects for Arrays

- -Every array has an associated Class object, shared with all other arrays with the same component type. The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable.

- -

This is shown by the following example code:

-
class Test {
-	public static void main(String[] args) {
-		int[] ia = new int[3];
-		System.out.println(ia.getClass());
-		System.out.println(ia.getClass().getSuperclass());
-	}
-}
-
-which prints:

-

class [I
-class java.lang.Object
-
-where the string "[I" is the run-time type signature for the class object "array with component type int".

- - -

10.9 An Array of Characters is Not a String

- -In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).

- -A String object is immutable, that is, its contents never change, while an array of char has mutable elements. The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters.

- - -

10.10 Array Store Exception

- -If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A.

- -

Thus, the example:

-
class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-class Test {
-	public static void main(String[] args) {
-		ColoredPoint[] cpa = new ColoredPoint[10];
-		Point[] pa = cpa;
-		System.out.println(pa[1] == null);
-		try {
-			pa[0] = new Point();
-		} catch (ArrayStoreException e) {
-			System.out.println(e);
-		}
-	}
-}
-
-produces the output:

-

true
-java.lang.ArrayStoreException
-
-Here the variable pa has type Point[] and the variable cpa has as its value a reference to an object of type ColoredPoint[]. A ColoredPoint can be assigned to a Point; therefore, the value of cpa can be assigned to pa.

- -

A reference to this array pa, for example, testing whether pa[1] is null, will not result in a run-time type error. This is because the element of the array of type ColoredPoint[] is a ColoredPoint, and every ColoredPoint can stand in for a Point, since Point is the superclass of ColoredPoint.

- -

On the other hand, an assignment to the array pa can result in a run-time error. At compile time, an assignment to an element of pa is checked to make sure that the value assigned is a Point. But since pa holds a reference to an array of ColoredPoint, the assignment is valid only if the type of the value assigned at run-time is, more specifically, a ColoredPoint.

- -The Java virtual machine checks for such a situation at run-time to ensure that the assignment is valid; if not, an ArrayStoreException is thrown. More formally: an assignment to an element of an array whose type is A[], where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A.

-


- -

- Discussion -

-

- - If the element type of an array were not reifiable (§4.7), the virtual machine could not perform the store check described in the preceding paragraph. This is why creation of arrays of non-reifiable types is forbidden. One may declare variables of array types whose element type is not reifiable, but any attempt to assign them a value will give rise to an unchecked warning (§5.1.9).

-


- -

- -

- -

- - -


-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - Blocks and Statements - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 14

- -

Blocks and Statements

-

- -

- -The sequence of execution of a program is controlled by statements, which are executed for their effect and do not have values.

- -Some statements contain other statements as part of their structure; such other statements are substatements of the statement. We say that statement S immediately contains statement U if there is no statement T different from S and U such that S contains T and T contains U. In the same manner, some statements contain expressions (§15) as part of their structure.

- -The first section of this chapter discusses the distinction between normal and abrupt completion of statements (§14.1). Most of the remaining sections explain the various kinds of statements, describing in detail both their normal behavior and any special treatment of abrupt completion.

- -Blocks are explained first (§14.2), followed by local class declarations (§14.3) and local variable declaration statements (§14.4).

- -Next a grammatical maneuver that sidesteps the familiar "dangling else" problem (§14.5) is explained.

- -The last section (§14.21) of this chapter addresses the requirement that every statement be reachable in a certain technical sense.

- -

- -

- - -

14.1 Normal and Abrupt Completion of Statements

- -If all the steps are carried out as described, with no indication of abrupt completion, the statement is said to complete normally. However, certain events may prevent a statement from completing normally:

-

-If such an event occurs, then execution of one or more statements may be terminated before all steps of their normal mode of execution have completed; such statements are said to complete abruptly.

- -An abrupt completion always has an associated reason, which is one of the following:

-

-The terms "complete normally" and "complete abruptly" also apply to the evaluation of expressions (§15.6). The only reason an expression can complete abruptly is that an exception is thrown, because of either a throw with a given value (§14.18) or a run-time exception or error (§11, §15.6).

- -If a statement evaluates an expression, abrupt completion of the expression always causes the immediate abrupt completion of the statement, with the same reason. All succeeding steps in the normal mode of execution are not performed.

- -Unless otherwise specified in this chapter, abrupt completion of a substatement causes the immediate abrupt completion of the statement itself, with the same reason, and all succeeding steps in the normal mode of execution of the statement are not performed.

- -Unless otherwise specified, a statement completes normally if all expressions it evaluates and all substatements it executes complete normally.

- - -

14.2 Blocks

- -A block is a sequence of statements, local class declarations and local variable declaration statements within braces.

-

-
-Block:
-        { BlockStatementsopt }
-
-BlockStatements:
-        BlockStatement
-        BlockStatements BlockStatement
-
-BlockStatement:
-        LocalVariableDeclarationStatement
-        ClassDeclaration
-        Statement
-        
-
-A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.

- - -

14.3 Local Class Declarations

- -A local class is a nested class (§8) that is not a member of any class and that has a name. All local classes are inner classes (§8.1.3). Every local class declaration statement is immediately contained by a block. Local class declaration statements may be intermixed freely with other kinds of statements in the block.

- -The scope of a local class immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration. The scope of a local class immediately enclosed by in a switch block statement group (§14.11)is the rest of the immediately enclosing switch block statement group, including its own class declaration.

- -The name of a local class C may not be redeclared as a local class of the directly enclosing method, constructor, or initializer block within the scope of C, or a compile-time error occurs. However, a local class declaration may be shadowed (§6.3.1) anywhere inside a class declaration nested within the local class declaration's scope. A local class does not have a canonical name, nor does it have a fully qualified name.

- -It is a compile-time error if a local class declaration contains any one of the following access modifiers: public, protected, private, or static.

- -

Here is an example that illustrates several aspects of the rules given above:

-
class Global {
-        class Cyclic {}
-        void foo() {
-                new Cyclic(); // create a Global.Cyclic
-                class Cyclic extends Cyclic{}; // circular definition
-                {
-                        class Local{};
-                        {
-                                class Local{}; // compile-time error
-                        }
-                        class Local{}; // compile-time error
-                        class AnotherLocal {
-                                void bar() {
-                                        class Local {}; // ok
-                                }
-                        }
-                }
-                class Local{}; // ok, not in scope of prior Local
-}
-
-The first statement of method foo creates an instance of the member class Global.Cyclic rather than an instance of the local class Cyclic, because the local class declaration is not yet in scope.

- -

The fact that the scope of a local class encompasses its own declaration (not only its body) means that the definition of the local class Cyclic is indeed cyclic because it extends itself rather than Global.Cyclic. Consequently, the declaration of the local class Cyclic will be rejected at compile time.

- -

Since local class names cannot be redeclared within the same method (or constructor or initializer, as the case may be), the second and third declarations of Local result in compile-time errors. However, Local can be redeclared in the context of another, more deeply nested, class such as AnotherLocal.

- -

The fourth and last declaration of Local is legal, since it occurs outside the scope of any prior declaration of Local.

- - -

14.4 Local Variable Declaration Statements

- -A local variable declaration statement declares one or more local variable names.

-

-
-LocalVariableDeclarationStatement:
-        LocalVariableDeclaration ;
-
-LocalVariableDeclaration:
-        VariableModifiers Type VariableDeclarators
-        
-
-The following are repeated from §8.3 to make the presentation here clearer:

-

-
-VariableDeclarators:
-        VariableDeclarator
-        VariableDeclarators , VariableDeclarator
-
-VariableDeclarator:
-        VariableDeclaratorId
-        VariableDeclaratorId = VariableInitializer
-
-VariableDeclaratorId:
-        Identifier
-        VariableDeclaratorId [ ]
-
-VariableInitializer:
-        Expression
-        ArrayInitializer
-        
-
-Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.

- -A local variable declaration can also appear in the header of a for statement (§14.14). In this case it is executed in the same manner as if it were part of a local variable declaration statement.

- - -

14.4.1 Local Variable Declarators and Types

- -Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator.

- -If the optional keyword final appears at the start of the declarator, the variable being declared is a final variable(§4.12.4).

- -If an annotation a on a local variable declaration corresponds to an annotation type T, and T has a (meta-)annotation m that corresponds to annotation.Target, then m must have an element whose value is annotation.ElementType.LOCAL_VARIABLE, or a compile-time error occurs. Annotation modifiers are described further in (§9.7).

- -The type of the variable is denoted by the Type that appears in the local variable declaration, followed by any bracket pairs that follow the Identifier in the declarator.

- -

Thus, the local variable declaration:

-
int a, b[], c[][];
-
-is equivalent to the series of declarations:

-

int a;
-int[] b;
-int[][] c;
-
-Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rule, however, also means that the local variable declaration:

-

float[][] f[][], g[][][], h[];                                                                                                 // Yechh!
-
-is equivalent to the series of declarations:

-

float[][][][] f;
-float[][][][][] g;
-float[][][] h;
-
-We do not recommend such "mixed notation" for array declarations.

- -A local variable of type float always contains a value that is an element of the float value set (§4.2.3); similarly, a local variable of type double always contains a value that is an element of the double value set. It is not permitted for a local variable of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a local variable of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.

- - -

14.4.2 Scope of Local Variable Declarations

- -The scope of a local variable declaration in a block (§14.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

- -The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. The name of a local variable v may not be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. However, a local variable of a method or initializer block may be shadowed (§6.3.1) anywhere inside a class declaration nested within the scope of the local variable.

- -A local variable cannot be referred to using a qualified name (§6.6), only a simple name.

- -

The example:

-
class Test {
-        static int x;
-        public static void main(String[] args) {
-                int x = x;
-        }
-}
-
-causes a compile-time error because the initialization of x is within the scope of the declaration of x as a local variable, and the local x does not yet have a value and cannot be used.

- -

The following program does compile:

-
class Test {
-        static int x;
-        public static void main(String[] args) {
-                int x = (x=2)*2;
-                System.out.println(x);
-        }
-}
-
-because the local variable x is definitely assigned (§16) before it is used. It prints:

-

4
-
- -

Here is another example:

-
-class Test {
-        public static void main(String[] args) {
-                System.out.print("2+1=");
-                int two = 2, three = two + 1;
-                System.out.println(three);
-        }
-}
-
-which compiles correctly and produces the output:

-

2+1=3
-
-The initializer for three can correctly refer to the variable two declared in an earlier declarator, and the method invocation in the next line can correctly refer to the variable three declared earlier in the block.

- -The scope of a local variable declared in a for statement is the rest of the for statement, including its own initializer.

- -If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.

- -

Thus the following example does not compile:

-
class Test {
-        public static void main(String[] args) {
-                int i;
-                for (int i = 0; i < 10; i++)
-                        System.out.println(i);
-        }
-}
-
- -

This restriction helps to detect some otherwise very obscure bugs. A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well. Hence, the following example compiles without error:

-
-class Test {
-        public static void main(String[] args) {
-                int i;
-                class Local {
-                        {
-                                for (int i = 0; i < 10; i++)
-                                System.out.println(i);
-                        }
-                }
-                new Local();
-        }
-}
-
- -

On the other hand, local variables with the same name may be declared in two separate blocks or for statements neither of which contains the other. Thus:

-
-class Test {
-        public static void main(String[] args) {
-                for (int i = 0; i < 10; i++)
-                        System.out.print(i + " ");
-                for (int i = 10; i > 0; i--)
-                        System.out.print(i + " ");
-                System.out.println();
-        }
-}
-
-compiles without error and, when executed, produces the output:

-

0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
-
- -

14.4.3 Shadowing of Names by Local Variables

- -If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable. Similarly, if a name is already declared as a variable or parameter name, then that outer declaration is shadowed throughout the scope of the local variable (provided that the shadowing does not cause a compile-time error under the rules of §14.4.2). The shadowed name can sometimes be accessed using an appropriately qualified name.

- -

For example, the keyword this can be used to access a shadowed field x, using the form this.x. Indeed, this idiom typically appears in constructors (§8.8):

-
class Pair {
-        Object first, second;
-        public Pair(Object first, Object second) {
-                this.first = first;
-                this.second = second;
-        }
-}
-
-In this example, the constructor takes parameters having the same names as the fields to be initialized. This is simpler than having to invent different names for the parameters and is not too confusing in this stylized context. In general, however, it is considered poor style to have local variables with the same names as fields.

- - -

14.4.4 Execution of Local Variable Declarations

- -A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable. If a declarator does not have an initialization expression, then a Java compiler must prove, using exactly the algorithm given in §16, that every reference to the variable is necessarily preceded by execution of an assignment to the variable. If this is not the case, then a compile-time error occurs.

- -Each initialization (except the first) is executed only if the evaluation of the preceding initialization expression completes normally. Execution of the local variable declaration completes normally only if evaluation of the last initialization expression completes normally; if the local variable declaration contains no initialization expressions, then executing it always completes normally.

- - -

14.5 Statements

- -There are many kinds of statements in the Java programming language. Most correspond to statements in the C and C++ languages, but some are unique.

- -As in C and C++, the if statement of the Java programming language suffers from the so-called "dangling else problem," illustrated by this misleadingly formatted example:

-


-if (door.isOpen())
-        if (resident.isVisible())
-                resident.greet("Hello!");
-else door.bell.ring();          // A "dangling else"
-
-

-The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement. The Java programming language, like C and C++ and many programming languages before them, arbitrarily decree that an else clause belongs to the innermost if to which it might possibly belong. This rule is captured by the following grammar:

-

-
-Statement:
-        StatementWithoutTrailingSubstatement
-        LabeledStatement
-        IfThenStatement
-        IfThenElseStatement
-        WhileStatement
-        ForStatement
-
-StatementWithoutTrailingSubstatement:
-        Block
-        EmptyStatement
-        ExpressionStatement
-        AssertStatement
-        SwitchStatement
-        DoStatement
-        BreakStatement
-        ContinueStatement
-        ReturnStatement
-        SynchronizedStatement
-        ThrowStatement
-        TryStatement
-
-StatementNoShortIf:
-        StatementWithoutTrailingSubstatement
-        LabeledStatementNoShortIf
-        IfThenElseStatementNoShortIf
-        WhileStatementNoShortIf
-        ForStatementNoShortIf
-        
-
-

- -The following are repeated from §14.9 to make the presentation here clearer:

- -

-

-
-IfThenStatement:
-        if ( Expression ) Statement
-
-IfThenElseStatement:
-        if ( Expression ) StatementNoShortIf else Statement
-
-IfThenElseStatementNoShortIf:
-        if ( Expression ) StatementNoShortIf else StatementNoShortIf
-
-
-

- -Statements are thus grammatically divided into two categories: those that might end in an if statement that has no else clause (a "short if statement") and those that definitely do not. Only statements that definitely do not end in a short if statement may appear as an immediate substatement before the keyword else in an if statement that does have an else clause.

- -

This simple rule prevents the "dangling else" problem. The execution behavior of a statement with the "no short if" restriction is identical to the execution behavior of the same kind of statement without the "no short if" restriction; the distinction is drawn purely to resolve the syntactic difficulty.

- - - -

14.6 The Empty Statement

- -An empty statement does nothing.

-

-
-EmptyStatement:
-        ;
-        
-
-Execution of an empty statement always completes normally.

- - -

14.7 Labeled Statements

- -Statements may have label prefixes.

-

-
-LabeledStatement:
-        Identifier : Statement
-
-LabeledStatementNoShortIf:
-        Identifier : StatementNoShortIf
-
-
-The Identifier is declared to be the label of the immediately contained Statement.

- -Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.

- -Let l be a label, and let m be the immediately enclosing method, constructor, instance initializer or static initializer. It is a compile-time error if l shadows (§6.3.1) the declaration of another label immediately enclosed in m.

- -There is no restriction against using the same identifier as a label and as the name of a package, class, interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not obscure (§6.3.2) a package, class, interface, method, field, parameter, or local variable with the same name. Use of an identifier as a class, interface, method, field, local variable or as the parameter of an exception handler (§14.20) does not obscure a statement label with the same name.

- -A labeled statement is executed by executing the immediately contained Statement. If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason.

- - -

14.8 Expression Statements

- -Certain kinds of expressions may be used as statements by following them with semicolons:

-

-
-ExpressionStatement:
-        StatementExpression ;
-
-StatementExpression:
-        Assignment
-        PreIncrementExpression
-        PreDecrementExpression
-        PostIncrementExpression
-        PostDecrementExpression
-        MethodInvocation
-        ClassInstanceCreationExpression
-        
-
-An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.

- -

Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements. Note that the Java programming language does not allow a "cast to void"-void is not a type-so the traditional C trick of writing an expression statement such as:

-
(void) ... ;           // incorrect!
-
-does not work. On the other hand, the language allows all the most useful kinds of expressions in expressions statements, and it does not require a method invocation used as an expression statement to invoke a void method, so such a trick is almost never needed. If a trick is needed, either an assignment statement (§15.26) or a local variable declaration statement (§14.4) can be used instead.

- - -

14.9 The if Statement

- -The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.

-

-
-IfThenStatement:
-        if ( Expression ) Statement
-
-IfThenElseStatement:
-        if ( Expression ) StatementNoShortIf else Statement
-
-IfThenElseStatementNoShortIf:
-        if ( Expression ) StatementNoShortIf else StatementNoShortIf
-
-The Expression must have type boolean or Boolean, or a compile-time error occurs.

- - -

14.9.1 The if-then Statement

- -An if-then statement is executed by first evaluating the Expression. If the result is of type Boolean, it is subject to unboxing conversion (§5.1.8). If evaluation of the Expression or the subsequent unboxing conversion (if any) completes abruptly for some reason, the if-then statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

-

- -

14.9.2 The if-then-else Statement

- -An if-then-else statement is executed by first evaluating the Expression. If the result is of type Boolean, it is subject to unboxing conversion (§5.1.8). If evaluation of the Expression or the subsequent unboxing conversion (if any) completes abruptly for some reason, then the if-then-else statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

-

- -

14.10 The assert Statement

- -An assertion is a statement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, evaluation of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to false. If the assertion is disabled, evaluation of the assertion has no effect whatsoever.

-

-
-AssertStatement:
-
-        assert Expression1 ;
-
-   assert Expression1 : Expression2 ;
-
-
-It is a compile-time error if Expression1 does not have type boolean or Boolean. In the second form of the assert statement, it is a compile-time error if Expression2 is void (§15.1).

- -Assertions may be enabled or disabled on a per-class basis. At the time a class is initialized (§12.4.2), prior to the execution of any field initializers for class variables (§8.3.2.1) and static initializers (§8.7), the class's class loader determines whether assertions are enabled or disabled as described below. Once a class has been initialized, its assertion status (enabled or disabled) does not change.

- -


-

-Discussion -

-

- There is one case that demands special treatment. Recall that the assertion status of a class is set at the time it is initialized. It is possible, though generally not desirable, to execute methods or constructors prior to initialization. This can happen when a class hierarchy contains a circularity in its static initialization, as in the following example:

-

public class Foo {
-    public static void main(String[] args) {
-                Baz.testAsserts(); 
-                // Will execute after Baz is initialized.
-    }
-}
-class Bar {
-    static {
-                Baz.testAsserts(); 
-                // Will execute before Baz is initialized!
-    }
-}
-class Baz extends Bar {
-    static void testAsserts(){
-                boolean enabled = false;
-                assert enabled = true;
-                System.out.println("Asserts " + 
-                        (enabled ? "enabled" : "disabled"));
-    }
-}
-
- - Invoking Baz.testAsserts() causes Baz to get initialized. Before this can happen, Bar must get initialized. Bar's static initializer again invokes Baz.testAsserts(). Because initialization of Baz is already in progress by the current thread, the second invocation executes immediately, though Baz is not initialized (JLS 12.4.2).

-


-

- -If an assert statement executes before its class is initialized, as in the above example, the execution must behave as if assertions were enabled in the class.

-


- -

- Discussion -

-

- - In other words, if the program above is executed without enabling assertions, it must print:

-

Asserts enabled
-Asserts disabled
-
-
-
-

-An assert statement is enabled if and only if the top-level class (§8) that lexically contains it enables assertions. Whether or not a top-level class enables assertions is determined by its defining class loader before the class is initialized (§12.4.2), and cannot be changed thereafter.

- -An assert statement causes the enclosing top level class (if it exists) to be initialized, if it has not already been initialized (§12.4.1).

- -


-

- Discussion -

-

- - Note that an assertion that is enclosed by a top-level interface does not cause initialization.

- -Usually, the top level class enclosing an assertion will already be initialized. However, if the assertion is located within a static nested class, it may be that the initialization has nottaken place.

- -


-

- -A disabled assert statement does nothing. In particular neither Expression1 nor Expression2 (if it is present) are evaluated. Execution of a disabled assert statement always completes normally.

- -An enabled assert statement is executed by first evaluating Expression1. If the result is of type Boolean, it is subject to unboxing conversion (§5.1.8). If evaluation of Expression1 or the subsequent unboxing conversion (if any) completes abruptly for some reason, the assert statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the value of Expression1 :

-

-

-


- -

- Discussion -

-

- - For example, after unmarshalling all of the arguments from a data buffer, a programmer might assert that the number of bytes of data remaining in the buffer is zero. By verifying that the boolean expression is indeed true, the system corroborates the programmer's knowledge of the program and increases one's confidence that the program is free of bugs.

- -Typically, assertion-checking is enabled during program development and testing, and disabled for deployment, to improve performance.

- -Because assertions may be disabled, programs must not assume that the expressions contained in assertions will be evaluated. Thus, these boolean expressions should generally be free of side effects:

- -Evaluating such a boolean expression should not affect any state that is visible after the evaluation is complete. It is not illegal for a boolean expression contained in an assertion to have a side effect, but it is generally inappropriate, as it could cause program behavior to vary depending on whether assertions were enabled or disabled.

- -Along similar lines, assertions should not be used for argument-checking in public methods. Argument-checking is typically part of the contract of a method, and this contract must be upheld whether assertions are enabled or disabled.

- -Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException or NullPointerException). An assertion failure will not throw an appropriate exception. Again, it is not illegal to use assertions for argument checking on public methods, but it is generally inappropriate. It is intended that AssertionError never be caught, but it is possible to do so, thus the rules for try statements should treat assertions appearing in a try block similarly to the current treatment of throw statements.

-


- -

- - -

14.11 The switch Statement

- -The switch statement transfers control to one of several statements depending on the value of an expression.

-

-
-SwitchStatement:
-        switch ( Expression ) SwitchBlock
-
-SwitchBlock:
-        { SwitchBlockStatementGroupsopt SwitchLabelsopt }
-
-SwitchBlockStatementGroups:
-        SwitchBlockStatementGroup
-        SwitchBlockStatementGroups SwitchBlockStatementGroup
-
-SwitchBlockStatementGroup:
-        SwitchLabels BlockStatements
-
-SwitchLabels:
-        SwitchLabel
-        SwitchLabels SwitchLabel
-
-SwitchLabel:
-        case ConstantExpression :
-        case EnumConstantName :
-        default :
-
-EnumConstantName:
-        Identifier
-        
-
-The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type (§8.9), or a compile-time error occurs.

- -The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.28) in the case labels.

- -All of the following must be true, or a compile-time error will result:

-

- -

-


-

- Discussion -

-

- - The prohibition against using null as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, such as a boxed primitive type or an enum, a run-time error will occur if the expression evaluates to null at run-time.

- -It follows that if the switch expression is of an enum type, the possible values of the switch labels must all be enum constants of that type.

- -Compilers are encouraged (but not required) to provide a warning if a switch on an enum-valued expression lacks a default case and lacks cases for one or more of the enum type's constants. (Such a statement will silently do nothing if the expression evaluates to one of the missing constants.)

-


- - -

In C and C++ the body of a switch statement can be a statement and statements with case labels do not have to be immediately contained by that statement. Consider the simple loop:

-
for (i = 0; i < n; ++i) foo();
-
-where n is known to be positive. A trick known as Duff's device can be used in C or C++ to unroll the loop, but this is not valid code in the Java programming language:

-

int q = (n+7)/8;
-switch (n%8) {
-case 0:         do {    foo();          // Great C hack, Tom,
-case 7:                 foo();          // but it's not valid here.
-case 6:                 foo();
-case 5:                 foo();
-case 4:                 foo();
-case 3:                 foo();
-case 2:                 foo();
-case 1:                 foo();
-                } while (--q > 0);
-}
-
-Fortunately, this trick does not seem to be widely known or used. Moreover, it is less needed nowadays; this sort of code transformation is properly in the province of state-of-the-art optimizing compilers.

- -When the switch statement is executed, first the Expression is evaluated. If the Expression evaluates to null, a NullPointerException is thrown and the entire switch statement completes abruptly for that reason. Otherwise, if the result is of a reference type, it is subject to unboxing conversion (§5.1.8). If evaluation of the Expression or the subsequent unboxing conversion (if any) completes abruptly for some reason, the switch statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the Expression with each case constant. Then there is a choice:

-

-If any statement immediately contained by the Block body of the switch statement completes abruptly, it is handled as follows:

-

-As in C and C++, execution of statements in a switch block "falls through labels."

- -

For example, the program:

-
class Toomany {
-        static void howMany(int k) {
-                switch (k) {
-                case 1:                 System.out.print("one ");
-                case 2:                 System.out.print("too ");
-                case 3:                 System.out.println("many");
-                }
-        }
-        public static void main(String[] args) {
-                howMany(3);
-                howMany(2);
-                howMany(1);
-        }
-}
-
-contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints:

-

many
-too many
-one too many
-
-If code is not to fall through case to case in this manner, then break statements should be used, as in this example:

-

class Twomany {
-        static void howMany(int k) {
-                switch (k) {
-                case 1:         System.out.println("one");
-                                break;          // exit the switch
-                case 2:         System.out.println("two");
-                                break;          // exit the switch
-                case 3:         System.out.println("many");
-                                break;          // not needed, but good style
-                }
-        }
-        public static void main(String[] args) {
-                howMany(1);
-                howMany(2);
-                howMany(3);
-        }
-}
-
-This program prints:

-

one
-two
-many
-
- -

14.12 The while Statement

- -The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false.

-

-
-WhileStatement:
-        while ( Expression ) Statement
-
-WhileStatementNoShortIf:
-        while ( Expression ) StatementNoShortIf
-
-The Expression must have type boolean or Boolean, or a compile-time error occurs.

- -A while statement is executed by first evaluating the Expression. If the result is of type Boolean, it is subject to unboxing conversion (§5.1.8). If evaluation of the Expression or the subsequent unboxing conversion (if any) completes abruptly for some reason, the while statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

-

-If the (possibly unboxed) value of the Expression is false the first time it is evaluated, then the Statement is not executed.

- - -

14.12.1 Abrupt Completion

- -Abrupt completion of the contained Statement is handled in the following manner:

-

- - - -

14.13 The do Statement

- -The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false.

-

-
-DoStatement:
-        do Statement while ( Expression ) ;
-
-The Expression must have type boolean or Boolean, or a compile-time error occurs.

- -A do statement is executed by first executing the Statement. Then there is a choice:

-

-Executing a do statement always executes the contained Statement at least once.

- - -

14.13.1 Abrupt Completion

- -Abrupt completion of the contained Statement is handled in the following manner:

-

- -

14.13.2 Example of do statement

- -The following code is one possible implementation of the toHexString method of class Integer:

-

public static String toHexString(int i) {
-        StringBuffer buf = new StringBuffer(8);
-        do {
-                buf.append(Character.forDigit(i & 0xF, 16));
-                i >>>= 4;
-        } while (i != 0);
-        return buf.reverse().toString();
-}
-
-Because at least one digit must be generated, the do statement is an appropriate control structure.

- - -

14.14 The for Statement

- -

-

-
-ForStatement:
-        BasicForStatement
-        EnhancedForStatement
-
-
-The for statement has two forms:

-

- -

14.14.1 The basic for Statement

- -The basic for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

-

-
-BasicForStatement:
-        for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
-
-ForStatementNoShortIf:
-        for ( ForInitopt ; Expressionopt ; ForUpdateopt )
-         StatementNoShortIf
-
-ForInit:
-        StatementExpressionList
-        LocalVariableDeclaration
-
-ForUpdate:
-        StatementExpressionList
-
-StatementExpressionList:
-        StatementExpression
-        StatementExpressionList , StatementExpression
-        
-
-The Expression must have type boolean or Boolean, or a compile-time error occurs.

- - -

14.14.1.1 Initialization of for statement

- -A for statement is executed by first executing the ForInit code:

-

-If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement (§14.4) appearing in a block. The scope of a local variable declared in the ForInit part of a basic for statement (§14.14) includes all of the following:

-

-If execution of the local variable declaration completes abruptly for any reason, the for statement completes abruptly for the same reason.

-

- -

14.14.1.2 Iteration of for statement

- -Next, a for iteration step is performed, as follows:

-

-If the (possibly unboxed) value of the Expression is false the first time it is evaluated, then the Statement is not executed.

- -If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement.

- - -

14.14.1.3 Abrupt Completion of for statement

- -Abrupt completion of the contained Statement is handled in the following manner:

-

- -

14.14.2 The enhanced for statement

- -The enhanced for statement has the form:

- -

-

-
-EnhancedForStatement:
-        for ( VariableModifiersopt Type Identifier: Expression) Statement
-
-The Expression must either have type Iterable or else it must be of an array type (§10.1), or a compile-time error occurs.

- -The scope of a local variable declared in the FormalParameter part of an enhanced for statement (§14.14) is the contained Statement

- -The meaning of the enhanced for statement is given by translation into a basic for statement.

- -If the type of Expression is a subtype of Iterable, then let I be the type of the expression Expression.iterator(). The enhanced for statement is equivalent to a basic for statement of the form:

-


-for (I #i = Expression.iterator(); #i.hasNext(); ) {
-
        VariableModifiersopt Type Identifier = #i.next();
-   Statement
-}
-
-Where #i is a compiler-generated identifier that is distinct from any other identifiers (compiler-generated or otherwise) that are in scope (§6.3) at the point where the enhanced for statement occurs.

- -Otherwise, the Expression necessarily has an array type, T[]. Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement. Then the meaning of the enhanced for statement is given by the following basic for statement:

-


-T[] a = Expression;
-L1: L2: ... Lm:
-for (int i = 0; i < a.length; i++) {
-        VariableModifiersopt Type Identifier = a[i];
-        Statement
-}
-
-Where a and i are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

- -


-

- Discussion -

-

- - The following example, which calculates the sum of an integer array, shows how enhanced for works for arrays:

-

    int sum(int[] a) {
-        int sum = 0;
-        for (int i : a)
-            sum += i;
-        return sum;
-    }
-        
- - Here is an example that combines the enhanced for statement with auto-unboxing to translate a histogram into a frequency table:

-

-    Map<String, Integer> histogram = ...;
-    double total = 0;
-    for (int i : histogram.values())
-        total += i;
-    for (Map.Entry<String, Integer> e : histogram.entrySet())
-        System.out.println(e.getKey() + "       " + e.getValue() / total);
-
-
-
-

- -

14.15 The break Statement

- -A break statement transfers control out of an enclosing statement.

-

-
-BreakStatement:
-        break Identifieropt ;
-
-A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement of the immediately enclosing method or initializer block; this statement, which is called the break target, then immediately completes normally.

- -To be precise, a break statement with no label always completes abruptly, the reason being a break with no label. If no switch, while, do, or for statement in the immediately enclosing method, constructor or initializer encloses the break statement, a compile-time error occurs.

- -A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a while, do, for, or switch statement. A break statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps.

- -To be precise, a break statement with label Identifier always completes abruptly, the reason being a break with label Identifier. If no labeled statement with Identifier as its label encloses the break statement, a compile-time error occurs.

- -It can be seen, then, that a break statement always completes abruptly.

- -

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break statement.

- -

In the following example, a mathematical graph is represented by an array of arrays. A graph consists of a set of nodes and a set of edges; each edge is an arrow that points from some node to some other node, or from a node to itself. In this example it is assumed that there are no redundant edges; that is, for any two nodes P and Q, where Q may be the same as P, there is at most one edge from P to Q. Nodes are represented by integers, and there is an edge from node i to node edges[i][j] for every i and j for which the array reference edges[i][j] does not throw an IndexOutOfBoundsException.

- -

The task of the method loseEdges, given integers i and j, is to construct a new graph by copying a given graph but omitting the edge from node i to node j, if any, and the edge from node j to node i, if any:

-
-class Graph {
-        int edges[][];
-                public Graph(int[][] edges) { this.edges = edges; }
-        public Graph loseEdges(int i, int j) {
-                int n = edges.length;
-                int[][] newedges = new int[n][];
-                for (int k = 0; k < n; ++k) {
-                        edgelist: {
-                                int z;
-                                search: {
-                                        if (k == i) {
-                                                for (z = 0; z < edges[k].length; ++z)
-                                                        if (edges[k][z] == j)
-                                                                break search;
-                                        } else if (k == j) {
-                                                for (z = 0; z < edges[k].length; ++z)
-                                                        if (edges[k][z] == i)
-                                                                break search;
-                                        }
-                                        // No edge to be deleted; share this list.
-                                        newedges[k] = edges[k];
-                                        break edgelist;
-                                } //search
-                                // Copy the list, omitting the edge at position z.
-                                int m = edges[k].length - 1;
-                                int ne[] = new int[m];
-                                System.arraycopy(edges[k], 0, ne, 0, z);
-                                System.arraycopy(edges[k], z+1, ne, z, m-z);
-                                newedges[k] = ne;
-                        } //edgelist
-                }
-                return new Graph(newedges);
-        }
-}
-
-Note the use of two statement labels, edgelist and search, and the use of break statements. This allows the code that copies a list, omitting one edge, to be shared between two separate tests, the test for an edge from node i to node j, and the test for an edge from node j to node i.

- - -

14.16 The continue Statement

- -A continue statement may occur only in a while, do, or for statement; statements of these three kinds are called iteration statements. Control passes to the loop-continuation point of an iteration statement.

-

-
-ContinueStatement:
-        continue Identifieropt ;
-
-A continue statement with no label attempts to transfer control to the innermost enclosing while, do, or for statement of the immediately enclosing method or initializer block; this statement, which is called the continue target, then immediately ends the current iteration and begins a new one.

- -To be precise, such a continue statement always completes abruptly, the reason being a continue with no label. If no while, do, or for statement of the immediately enclosing method or initializer block encloses the continue statement, a compile-time error occurs.

- -A continue statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; that statement, which is called the continue target, then immediately ends the current iteration and begins a new one. The continue target must be a while, do, or for statement or a compile-time error occurs. A continue statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps.

- -More precisely, a continue statement with label Identifier always completes abruptly, the reason being a continue with label Identifier. If no labeled statement with Identifier as its label contains the continue statement, a compile-time error occurs.

- -It can be seen, then, that a continue statement always completes abruptly.

- -See the descriptions of the while statement (§14.12), do statement (§14.13), and for statement (§14.14) for a discussion of the handling of abrupt termination because of continue.

- -

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the continue target whose try blocks contain the continue statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the continue target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a continue statement.

- -

In the Graph example in the preceding section, one of the break statements is used to finish execution of the entire body of the outermost for loop. This break can be replaced by a continue if the for loop itself is labeled:

-
class Graph {
-        . . .
-        public Graph loseEdges(int i, int j) {
-                int n = edges.length;
-                int[][] newedges = new int[n][];
-                edgelists: for (int k = 0; k < n; ++k) {
-                        int z;
-                        search: {
-                                if (k == i) {
-                                        . . .
-                                } else if (k == j) {
-                                        . . .
-                                }
-                                newedges[k] = edges[k];
-                                continue edgelists;
-                        } // search
-                        . . .
-                } // edgelists
-                return new Graph(newedges);
-        }
-}
-
-Which to use, if either, is largely a matter of programming style.

- - -

14.17 The return Statement

- -A return statement returns control to the invoker of a method (§8.4, §15.12) or constructor (§8.8, §15.9).

-

-
-ReturnStatement:
-        return Expressionopt ;
-
-A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.8). A compile-time error occurs if a return statement appears within an instance initializer or a static initializer (§8.7). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it.

- -To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.

- -A return statement with an Expression must be contained in a method declaration that is declared to return a value (§8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (§5.2) to the declared result type of the method, or a compile-time error occurs.

- -A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V. If the expression is of type float and is not FP-strict (§15.4), then the value may be an element of either the float value set or the float-extended-exponent value set (§4.2.3). If the expression is of type double and is not FP-strict, then the value may be an element of either the double value set or the double-extended-exponent value set.

- -It can be seen, then, that a return statement always completes abruptly.

- -

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the method or constructor whose try blocks contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

- - -

14.18 The throw Statement

- -A throw statement causes an exception (§11) to be thrown. The result is an immediate transfer of control (§11.3) that may exit multiple statements and multiple constructor, instance initializer, static initializer and field initializer evaluations, and method invocations until a try statement (§14.20) is found that catches the thrown value. If no such try statement is found, then execution of the thread (§17) that executed the throw is terminated (§11.3) after invocation of the uncaughtException method for the thread group to which the thread belongs.

-

-
-ThrowStatement:
-        throw Expression ;
-
-A throw statement can throw an exception type E iff the static type of the throw expression is E or a subtype of E, or the thrown expression can throw E.

- -The Expression in a throw statement must denote a variable or value of a reference type which is assignable (§5.2) to the type Throwable, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs:

-

-A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null value V, then the throw statement completes abruptly, the reason being a throw with value V. If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null. The throw statement then completes abruptly, the reason being a throw with value V'.

- -It can be seen, then, that a throw statement always completes abruptly.

- -If there are any enclosing try statements (§14.20) whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.

- -If a throw statement is contained in a method declaration, but its value is not caught by some try statement that contains it, then the invocation of the method completes abruptly because of the throw.

- -If a throw statement is contained in a constructor declaration, but its value is not caught by some try statement that contains it, then the class instance creation expression that invoked the constructor will complete abruptly because of the throw.

- -If a throw statement is contained in a static initializer (§8.7), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it. If at run-time, despite this check, the value is not caught by some try statement that contains the throw statement, then the value is rethrown if it is an instance of class Error or one of its subclasses; otherwise, it is wrapped in an ExceptionInInitializerError object, which is then thrown (§12.4.2).

- -If a throw statement is contained in an instance initializer (§8.6), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it, or the type of the thrown exception (or one of its superclasses) occurs in the throws clause of every constructor of the class.

- -By convention, user-declared throwable types should usually be declared to be subclasses of class Exception, which is a subclass of class Throwable (§11.5).

- -

- -

- - -

14.19 The synchronized Statement

- -A synchronized statement acquires a mutual-exclusion lock (§17.1) on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock.

-

-
-SynchronizedStatement:
-        synchronized ( Expression ) Block
-
-

- -The type of Expression must be a reference type, or a compile-time error occurs.

- -A synchronized statement is executed by first evaluating the Expression.

- -If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.

- -Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

- -Otherwise, let the non-null value of the Expression be V. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason.

- -Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.

- -The locks acquired by synchronized statements are the same as the locks that are acquired implicitly by synchronized methods; see §8.4.3.6. A single thread may hold a lock more than once.

- -

The example:

-
class Test {
-        public static void main(String[] args) {
-                Test t = new Test();
-                synchronized(t) {
-                        synchronized(t) {
-                                System.out.println("made it!");
-                        }
-                }
-        }
-}
-
-prints:

-

made it!
-
-This example would deadlock if a single thread were not permitted to lock a lock more than once.

- - -

14.20 The try statement

- -A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If the try statement has a finally clause, then another block of code is executed, no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.

-

-
-TryStatement:
-        try Block Catches
-        try Block Catchesopt Finally
-
-Catches:
-        CatchClause
-        Catches CatchClause
-
-CatchClause:
-        catch ( FormalParameter ) Block
-
-Finally:
-        finally Block
-
-

- - -The following is repeated from §8.4.1 to make the presentation here clearer:

-

-
-FormalParameter:
-        VariableModifiers Type VariableDeclaratorId
-        
-
-The following is repeated from §8.3 to make the presentation here clearer:

-

-
-VariableDeclaratorId:
-        Identifier
-        VariableDeclaratorId [ ]
-
-The Block immediately after the keyword try is called the try block of the try statement. The Block immediately after the keyword finally is called the finally block of the try statement.

- -A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass (not just a subtype) of Throwable, or a compile-time error occurs.In particular, it is a compile-time error if the declared type of the exception parameter is a type variable (§4.4). The scope of the parameter variable is the Block of the catch clause.

- -An exception parameter of a catch clause must not have the same name as a local variable or parameter of the method or initializer block immediately enclosing the catch clause, or a compile-time error occurs.

- -The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (§14.20) is the entire block associated with the catch.

- -Within the Block of the catch clause, the name of the parameter may not be redeclared as a local variable of the directly enclosing method or initializer block, nor may it be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method or initializer block, or a compile-time error occurs. However, an exception parameter may be shadowed (§6.3.1) anywhere inside a class declaration nested within the Block of the catch clause.

- -A try statement can throw an exception type E iff either:

-

-

- -It is a compile-time error if an exception parameter that is declared final is assigned to within the body of the catch clause.

- -It is a compile-time error if a catch clause catches checked exception type E1 but there exists no checked exception type E2 such that all of the following hold:

-

-unless E1 is the class Exception.

- -Exception parameters cannot be referred to using qualified names (§6.6), only by simple names.

- -Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its actual argument the thrown exception object.

- -A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.

- -Handling of the finally block is rather complex, so the two cases of a try statement with and without a finally block are described separately.

- - -

14.20.1 Execution of try-catch

- -A try statement without a finally block is executed by first executing the try block. Then there is a choice:

-

- -

In the example:

-
class BlewIt extends Exception {
-        BlewIt() { }
-        BlewIt(String s) { super(s); }
-}
-class Test {
-        static void blowUp() throws BlewIt { throw new BlewIt(); }
-        public static void main(String[] args) {
-                try {
-                        blowUp();
-                } catch (RuntimeException r) {
-                        System.out.println("RuntimeException:" + r);
-                } catch (BlewIt b) {
-                        System.out.println("BlewIt");
-                }
-        }
-}
-
-the exception BlewIt is thrown by the method blowUp. The try-catch statement in the body of main has two catch clauses. The run-time type of the exception is BlewIt which is not assignable to a variable of type RuntimeException, but is assignable to a variable of type BlewIt, so the output of the example is:

-

BlewIt
-
- -

14.20.2 Execution of try-catch-finally

- -A try statement with a finally block is executed by first executing the try block. Then there is a choice:

-

- -

The example:

-
class BlewIt extends Exception {
-        BlewIt() { }
-        BlewIt(String s) { super(s); }
-}
-class Test {
-        static void blowUp() throws BlewIt {
-                throw new NullPointerException();
-        }
-        public static void main(String[] args) {
-                try {
-                        blowUp();
-                } catch (BlewIt b) {
-                        System.out.println("BlewIt");
-                } finally {
-                        System.out.println("Uncaught Exception");
-                }
-        }
-}
-
-
-
-produces the output:

-

Uncaught Exception
-java.lang.NullPointerException
-        at Test.blowUp(Test.java:7)
-        at Test.main(Test.java:11)
-
-The NullPointerException (which is a kind of RuntimeException) that is thrown by method blowUp is not caught by the try statement in main, because a NullPointerException is not assignable to a variable of type BlewIt. This causes the finally clause to execute, after which the thread executing main, which is the only thread of the test program, terminates because of an uncaught exception, which typically results in printing the exception name and a simple backtrace. However, a backtrace is not required by this specification.

- -


-

- Discussion -

-

- - The problem with mandating a backtrace is that an exception can be created at one point in the program and thrown at a later one. It is prohibitively expensive to store a stack trace in an exception unless it is actually thrown (in which case the trace may be generated while unwinding the stack). Hence we do not mandate a back trace in every exception.

-


- -

- - -

14.21 Unreachable Statements

- -It is a compile-time error if a statement cannot be executed because it is unreachable. Every Java compiler must carry out the conservative flow analysis specified here to make sure all statements are reachable.

- -This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

- -

For example, a Java compiler will accept the code:

-
{
-        int n = 5;
-        while (n > 7) k = 2;
-}
-
-even though the value of n is known at compile time and in principle it can be known at compile time that the assignment to k can never be executed.

- -A Java compiler must operate according to the rules laid out in this section.

- -The rules in this section define two technical terms:

-

-The definitions here allow a statement to complete normally only if it is reachable.

- -To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."

- -The rules are as follows:

-

-

One might expect the if statement to be handled in the following manner, but these are not the rules that the Java programming language actually uses:

- -

This approach would be consistent with the treatment of other control structures. However, in order to allow the if statement to be used conveniently for "conditional compilation" purposes, the actual rules differ.

- -

-The actual rules for the if statement are as follows:

-

-

As an example, the following statement results in a compile-time error:

-
while (false) { x=3; }
-
-because the statement x=3; is not reachable; but the superficially similar case:

-

if (false) { x=3; }
-
-does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

- -

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

-
static final boolean DEBUG = false;
-
-and then write code such as:

-

if (DEBUG) { x=3; }
-
-The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

- -

This ability to "conditionally compile" has a significant impact on, and relationship to, binary compatibility (§13). If a set of classes that use such a "flag" variable are compiled and conditional code is omitted, it does not suffice later to distribute just a new version of the class or interface that contains the definition of the flag. A change to the value of a flag is, therefore, not binary compatible with preexisting binaries (§13.4.9). (There are other reasons for such incompatibility as well, such as the use of constants in case labels in switch statements; see §13.4.9.)

- - -
-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - - - - Expressions - - - - - - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-



- - -

-CHAPTER - 15

- -

Expressions

-

- -Much of the work in a program is done by evaluating expressions, either for their side effects, such as assignments to variables, or for their values, which can be used as arguments or operands in larger expressions, or to affect the execution sequence in statements, or both.

- -This chapter specifies the meanings of expressions and the rules for their evaluation.

- - -

15.1 Evaluation, Denotation, and Result

- -When an expression in a program is evaluated (executed), the result denotes one of three things:

-

-Evaluation of an expression can also produce side effects, because expressions may contain embedded assignments, increment operators, decrement operators, and method invocations.

- -An expression denotes nothing if and only if it is a method invocation (§15.12) that invokes a method that does not return a value, that is, a method declared void (§8.4). Such an expression can be used only as an expression statement (§14.8), because every other context in which an expression can appear requires the expression to denote something. An expression statement that is a method invocation may also invoke a method that produces a result; in this case the value returned by the method is quietly discarded.

- -Value set conversion (§5.1.13) is applied to the result of every expression that produces a value.

- -Each expression occurs in either:

-

- -

15.2 Variables as Values

- -If an expression denotes a variable, and a value is required for use in further evaluation, then the value of that variable is used. In this context, if the expression denotes a variable or a value, we may speak simply of the value of the expression.

- -If the value of a variable of type float or double is used in this manner, then value set conversion (§5.1.13) is applied to the value of the variable.

- - -

15.3 Type of an Expression

- -If an expression denotes a variable or a value, then the expression has a type known at compile time. The rules for determining the type of an expression are explained separately below for each kind of expression.

- -

The value of an expression is assignment compatible (§5.2) with the type of the expression, unless heap pollution (§4.12.2.1) occurs. Likewise the value stored in a variable is always compatible with the type of the variable, unless heap pollution occurs. In other words, the value of an expression whose type is T is always suitable for assignment to a variable of type T.

- -

Note that an expression whose type is a class type F that is declared final is guaranteed to have a value that is either a null reference or an object whose class is F itself, because final types have no subclasses.

- - -

15.4 FP-strict Expressions

- -If the type of an expression is float or double, then there is a question as to what value set (§4.2.3) the value of the expression is drawn from. This is governed by the rules of value set conversion (§5.1.13); these rules in turn depend on whether or not the expression is FP-strict.

- -Every compile-time constant expression (§15.28) is FP-strict. If an expression is not a compile-time constant expression, then consider all the class declarations, interface declarations, and method declarations that contain the expression. If any such declaration bears the strictfp modifier, then the expression is FP-strict.

- -If a class, interface, or method, X, is declared strictfp, then X and any class, interface, method, constructor, instance initializer, static initializer or variable initializer within X is said to be FP-strict. Note that an annotation (§9.7) element value (§9.6) is always FP-strict, because it is always a compile-time constant (§15.28).

- -It follows that an expression is not FP-strict if and only if it is not a compile-time constant expression and it does not appear within any declaration that has the strictfp modifier.

- -Within an FP-strict expression, all intermediate values must be elements of the float value set or the double value set, implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats. Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow.

- - -

15.5 Expressions and Run-Time Checks

- -If the type of an expression is a primitive type, then the value of the expression is of that same primitive type. But if the type of an expression is a reference type, then the class of the referenced object, or even whether the value is a reference to an object rather than null, is not necessarily known at compile time. There are a few places in the Java programming language where the actual class of a referenced object affects program execution in a manner that cannot be deduced from the type of the expression. They are as follows:

-

-Situations where the class of an object is not statically known may lead to run-time type errors.

- -In addition, there are situations where the statically known type may not be accurate at run-time. Such situations can arise in a program that gives rise to unchecked warnings. Such warnings are given in response to operations that cannot be statically guaranteed to be safe, and cannot immediately be subjected to dynamic checking because they involve non-reifiable (§4.7) types. As a result, dynamic checks later in the course of program execution may detect inconsistencies and result in run-time type errors.

- -

- -A run-time type error can occur only in these situations:

-

- -

15.6 Normal and Abrupt Completion of Evaluation

- -Every expression has a normal mode of evaluation in which certain computational steps are carried out. The following sections describe the normal mode of evaluation for each kind of expression. If all the steps are carried out without an exception being thrown, the expression is said to complete normally.

- -If, however, evaluation of an expression throws an exception, then the expression is said to complete abruptly. An abrupt completion always has an associated reason, which is always a throw with a given value.

- -Run-time exceptions are thrown by the predefined operators as follows:

-

-A method invocation expression can also result in an exception being thrown if an exception occurs that causes execution of the method body to complete abruptly. A class instance creation expression can also result in an exception being thrown if an exception occurs that causes execution of the constructor to complete abruptly. Various linkage and virtual machine errors may also occur during the evaluation of an expression. By their nature, such errors are difficult to predict and difficult to handle.

- -If an exception occurs, then evaluation of one or more expressions may be terminated before all steps of their normal mode of evaluation are complete; such expressions are said to complete abruptly. The terms "complete normally" and "complete abruptly" are also applied to the execution of statements (§14.1). A statement may complete abruptly for a variety of reasons, not just because an exception is thrown.

- -If evaluation of an expression requires evaluation of a subexpression, abrupt completion of the subexpression always causes the immediate abrupt completion of the expression itself, with the same reason, and all succeeding steps in the normal mode of evaluation are not performed.

- - -

15.7 Evaluation Order

- -The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

- -

It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

- - -

15.7.1 Evaluate Left-Hand Operand First

- -The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. For example, if the left-hand operand contains an assignment to a variable and the right-hand operand contains a reference to that same variable, then the value produced by the reference will reflect the fact that the assignment occurred first.

- -

Thus:

-
class Test {
-        public static void main(String[] args) {
-                int i = 2;
-                int j = (i=3) * i;
-                System.out.println(j);
-        }
-}
-
-prints:

-

9
-
-It is not permitted for it to print 6 instead of 9.

- -

If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied combining operation. So, for example, the test program:

-
class Test {
-        public static void main(String[] args) {
-                int a = 9;
-                a += (a = 3);                                                                   // first example
-                System.out.println(a);
-                int b = 9;
-                b = b + (b = 3);                                                                        // second example
-                System.out.println(b);
-        }
-}
-
-prints:

-

12
-12
-
-because the two assignment statements both fetch and remember the value of the left-hand operand, which is 9, before the right-hand operand of the addition is evaluated, thereby setting the variable to 3. It is not permitted for either example to produce the result 6. Note that both of these examples have unspecified behavior in C, according to the ANSI/ISO standard.

- -If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand appears to have been evaluated.

- -

Thus, the test program:

-
class Test {
-        public static void main(String[] args) {
-                int j = 1;
-                try {
-                        int i = forgetIt() / (j = 2);
-                } catch (Exception e) {
-                        System.out.println(e);
-                        System.out.println("Now j = " + j);
-                }
-        }
-        static int forgetIt() throws Exception {
-                throw new Exception("I'm outta here!");
-        }
-}
-
-prints:

-

java.lang.Exception: I'm outta here!
-Now j = 1
-
-That is, the left-hand operand forgetIt() of the operator / throws an exception before the right-hand operand is evaluated and its embedded assignment of 2 to j occurs.

- - -

15.7.2 Evaluate Operands before Operation

- -The Java programming language also guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

- -If the binary operator is an integer division / (§15.17.2) or integer remainder % (§15.17.3), then its execution may raise an ArithmeticException, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.

- -

So, for example, the program:

-
class Test {
-        public static void main(String[] args) {
-                int divisor = 0;
-                try {
-                        int i = 1 / (divisor * loseBig());
-                } catch (Exception e) {
-                        System.out.println(e);
-                }
-        }
-        static int loseBig() throws Exception {
-                throw new Exception("Shuffle off to Buffalo!");
-        }
-}
-
-always prints:

-

java.lang.Exception: Shuffle off to Buffalo!
-
-and not:

-

java.lang.ArithmeticException: / by zero
-
-since no part of the division operation, including signaling of a divide-by-zero exception, may appear to occur before the invocation of loseBig completes, even though the implementation may be able to detect or infer that the division operation would certainly result in a divide-by-zero exception.

- -

- - -

15.7.3 Evaluation Respects Parentheses and Precedence

- -Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence. An implementation may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects, even in the presence of multiple threads of execution (using the thread execution model in §17), for all possible computational values that might be involved.

- -In the case of floating-point calculations, this rule applies also for infinity and not-a-number (NaN) values. For example, !(x<y) may not be rewritten as x>=y, because these expressions have different values if either x or y is NaN or both are NaN.

- -Specifically, floating-point calculations that appear to be mathematically associative are unlikely to be computationally associative. Such computations must not be naively reordered.

- -

For example, it is not correct for a Java compiler to rewrite 4.0*x*0.5 as 2.0*x; while roundoff happens not to be an issue here, there are large values of x for which the first expression produces infinity (because of overflow) but the second expression produces a finite result.

- -

- -

So, for example, the test program:

-
strictfp class Test {
-        public static void main(String[] args) {
-                double d = 8e+307;
-                System.out.println(4.0 * d * 0.5);
-                System.out.println(2.0 * d);
-        }
-}
-
-prints:

-

Infinity
-1.6e+308
-
-because the first expression overflows and the second does not.

- -In contrast, integer addition and multiplication are provably associative in the Java programming language.

- -

For example a+b+c, where a, b, and c are local variables (this simplifying assumption avoids issues involving multiple threads and volatile variables), will always produce the same answer whether evaluated as (a+b)+c or a+(b+c); if the expression b+c occurs nearby in the code, a smart compiler may be able to use this common subexpression.

- - -

15.7.4 Argument Lists are Evaluated Left-to-Right

- -In a method or constructor invocation or class instance creation expression, argument expressions may appear within the parentheses, separated by commas. Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

- -

Thus:

-
class Test {
-        public static void main(String[] args) {
-                String s = "going, ";
-                print3(s, s, s = "gone");
-        }
-        static void print3(String a, String b, String c) {
-                System.out.println(a + b + c);
-        }
-}
-
-always prints:

-

going, going, gone
-
-because the assignment of the string "gone" to s occurs after the first two arguments to print3 have been evaluated.

- -If evaluation of an argument expression completes abruptly, no part of any argument expression to its right appears to have been evaluated.

- -

Thus, the example:

-
class Test {
-        static int id;
-        public static void main(String[] args) {
-                try {
-                        test(id = 1, oops(), id = 3);
-                } catch (Exception e) {
-                        System.out.println(e + ", id=" + id);
-                }
-        }
-        static int oops() throws Exception {
-                throw new Exception("oops");
-        }
-        static int test(int a, int b, int c) {
-                return a + b + c;
-        }
-}
-
-prints:

-

java.lang.Exception: oops, id=1
-
-because the assignment of 3 to id is not executed.

- - -

15.7.5 Evaluation Order for Other Expressions

- -The order of evaluation for some expressions is not completely covered by these general rules, because these expressions may raise exceptional conditions at times that must be specified. See, specifically, the detailed explanations of evaluation order for the following kinds of expressions:

-

- -

15.8 Primary Expressions

- -Primary expressions include most of the simplest kinds of expressions, from which all others are constructed: literals, class literals, field accesses, method invocations, and array accesses. A parenthesized expression is also treated syntactically as a primary expression.

-

-
-Primary:
-        PrimaryNoNewArray
-        ArrayCreationExpression
-
-PrimaryNoNewArray:
-        Literal
-        Type . class
-        void . class
-        this
-        ClassName.this
-        ( Expression )
-        ClassInstanceCreationExpression
-        FieldAccess
-        MethodInvocation
-        ArrayAccess
-        
-
- -

15.8.1 Lexical Literals

- -A literal (§3.10) denotes a fixed, unchanging value.

- -The following production from §3.10 is repeated here for convenience:

-

-
-Literal:
-        IntegerLiteral
-        FloatingPointLiteral
-        BooleanLiteral
-        CharacterLiteral
-        StringLiteral
-        NullLiteral
-        
-
-The type of a literal is determined as follows:

-

-Evaluation of a lexical literal always completes normally.

- -

- - -

15.8.2 Class Literals

- -A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a `.' and the token class. The type of a class literal, C.Class, where C is the name of a class, interface or array type, is Class<C>. If p is the name of a primitive type, let B be the type of an expression of type p after boxing conversion (§5.1.7). Then the type of p.class is Class<B>. The type of void.class is Class<Void>.

- -A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

- -It is a compile time error if any of the following occur:

-

-

- - -

15.8.3 this

- -The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

- -When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.

- -

In the example:

-
class IntVector {
-        int[] v;
-        boolean equals(IntVector other) {
-                if (this == other)
-                        return true;
-                if (v.length != other.v.length)
-                        return false;
-                for (int i = 0; i < v.length; i++)
-                        if (v[i] != other.v[i])
-                                return false;
-                return true;
-        }
-}
-
-the class IntVector implements a method equals, which compares two vectors. If the other vector is the same vector object as the one for which the equals method was invoked, then the check can skip the length and value comparisons. The equals method implements this check by comparing the reference to the other object to this.

- -The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body (§8.8.7).

- - -

15.8.4 Qualified this

- -Any lexically enclosing instance can be referred to by explicitly qualifying the keyword this.

- -Let C be the class denoted by ClassName. Let n be an integer such that C is the nth lexically enclosing class of the class in which the qualified this expression appears. The value of an expression of the form ClassName.this is the nth lexically enclosing instance of this (§8.1.3). The type of the expression is C. It is a compile-time error if the current class is not an inner class of class C or C itself.

- - -

15.8.5 Parenthesized Expressions

- -A parenthesized expression is a primary expression whose type is the type of the contained expression and whose value at run time is the value of the contained expression. If the contained expression denotes a variable then the parenthesized expression also denotes that variable.

- -The use of parentheses only effects the order of evaluation, with one fascinating exception.

- -


-

- Discussion -

-

- - Consider the case if the smallest possible negative value of type long. This value, 9223372036854775808L, is allowed only as an operand of the unary minus operator (§3.10.1). Therefore, enclosing it in parentheses, as in -(9223372036854775808L) causes a compile time error.

-


- - -

- -In particular, the presence or absence of parentheses around an expression does not (except for the case noted above) affect in any way:

-

- -

15.9 Class Instance Creation Expressions

- -A class instance creation expression is used to create new objects that are instances of classes.

-

-
-ClassInstanceCreationExpression:
-   new TypeArgumentsopt ClassOrInterfaceType ( ArgumentListopt )
-ClassBodyopt
-        Primary. new TypeArgumentsopt Identifier TypeArgumentsopt (
-ArgumentListopt ) ClassBodyopt
-
-ArgumentList:
-        Expression
-        ArgumentList , Expression
-        
-
-A class instance creation expression specifies a class to be instantiated, possibly followed by type arguments (if the class being instantiated is generic (§8.1.2)), followed by (a possibly empty) list of actual value arguments to the constructor. It is also possible to pass explicit type arguments to the constructor itself (if it is a generic constructor (§8.8.4)). The type arguments to the constructor immediately follow the keyword new. It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments (§4.5.1). Class instance creation expressions have two forms:

-

-A class instance creation expression can throw an exception type E iff either:

-

-Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (§15.9.5) and creates an instance of it.

- -We say that a class is instantiated when an instance of the class is created by a class instance creation expression. Class instantiation involves determining what class is to be instantiated, what the enclosing instances (if any) of the newly created instance are, what constructor should be invoked to create the new instance and what arguments should be passed to that constructor.

- - -

15.9.1 Determining the Class being Instantiated

- -If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:

-

-If a class instance creation expression does not declare an anonymous class, then:

-

-The type of the class instance creation expression is the class type being instantiated.

- - -

15.9.2 Determining Enclosing Instances

- -Let C be the class being instantiated, and let i the instance being created. If C is an inner class then i may have an immediately enclosing instance. The immediately enclosing instance of i (§8.1.3) is determined as follows:

-

-In addition, if C is an anonymous class, and the direct superclass of C, S, is an inner class then i may have an immediately enclosing instance with respect to S which is determined as follows:

-

- -

15.9.3 Choosing the Constructor and its Arguments

- -Let C be the class type being instantiated. To create an instance of C, i, a constructor of C is chosen at compile-time by the following rules:

-

-Note that the type of the class instance creation expression may be an anonymous class type, in which case the constructor being invoked is an anonymous constructor.

- - -

15.9.4 Run-time Evaluation of Class Instance Creation Expressions

- -At run time, evaluation of a class instance creation expression is as follows.

- -First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null, a NullPointerException is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason.

- -Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (§15.9.6).

- -The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (§4.12.5).

- -Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.

- -Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.8) and is described in detail in §12.5.

- -The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.

- - -

15.9.5 Anonymous Class Declarations

- -An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.

- -An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.2). An anonymous class is always implicitly final (§8.1.1.2).

- - -

15.9.5.1 Anonymous Constructors

- -An anonymous class cannot have an explicitly declared constructor. Instead, the compiler must automatically provide an anonymous constructor for the anonymous class. The form of the anonymous constructor of an anonymous class C with direct superclass S is as follows:

-

-In all cases, the throws clause of an anonymous constructor must list all the checked exceptions thrown by the explicit superclass constructor invocation statement contained within the anonymous constructor, and all checked exceptions thrown by any instance initializers or instance variable initializers of the anonymous class.

- -Note that it is possible for the signature of the anonymous constructor to refer to an inaccessible type (for example, if such a type occurred in the signature of the superclass constructor cs). This does not, in itself, cause any errors at either compile time or run time.

- - -

15.9.6 Example: Evaluation Order and Out-of-Memory Detection

- -If evaluation of a class instance creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs before any argument expressions are evaluated.

- -

So, for example, the test program:

-
class List {
-        int value;
-        List next;
-        static List head = new List(0);
-        List(int n) { value = n; next = head; head = this; }
-}
-class Test {
-        public static void main(String[] args) {
-                int id = 0, oldid = 0;
-                try {
-                        for (;;) {
-                                ++id;
-                                new List(oldid = id);
-                        }
-                } catch (Error e) {
-                        System.out.println(e + ", " + (oldid==id));
-                }
-        }
-}
-
-prints:

-

java.lang.OutOfMemoryError: List, false
-
-because the out-of-memory condition is detected before the argument expression oldid = id is evaluated.

- -

Compare this to the treatment of array creation expressions (§15.10), for which the out-of-memory condition is detected after evaluation of the dimension expressions (§15.10.3).

- - -

15.10 Array Creation Expressions

- -An array instance creation expression is used to create new arrays (§10).

-

-
-ArrayCreationExpression:
-   new PrimitiveType DimExprs Dimsopt
-        new ClassOrInterfaceType DimExprs Dimsopt
-      new PrimitiveType Dims ArrayInitializer
-        new ClassOrInterfaceType Dims ArrayInitializer
-        
-
-

-

-
-DimExprs:
-        DimExpr
-        DimExprs DimExpr
-
-DimExpr:
-        [ Expression ]
-
-Dims:
-        [ ]
-        Dims [ ]
-
-An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7). Otherwise, the ClassOrInterfaceType may name any named reference type, even an abstract class type (§8.1.1.1) or an interface type (§9).

- -


-

-Discussion -

-

- The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.

-


- -

- -The type of the creation expression is an array type that can denoted by a copy of the creation expression from which the new keyword and every DimExpr expression and array initializer have been deleted.

- -

For example, the type of the creation expression:

-
new double[3][3][]
-
-is:

-

double[][][]
-
-The type of each dimension expression within a DimExpr must be a type that is convertible (§5.1.8) to an integral type, or a compile-time error occurs. Each expression undergoes unary numeric promotion (§). The promoted type must be int, or a compile-time error occurs; this means, specifically, that the type of a dimension expression must not be long.

- -If an array initializer is provided, the newly allocated array will be initialized with the values provided by the array initializer as described in §10.6.

- - -

15.10.1 Run-time Evaluation of Array Creation Expressions

- -At run time, evaluation of an array creation expression behaves as follows. If there are no dimension expressions, then there must be an array initializer. The value of the array initializer is the value of the array creation expression. Otherwise:

- -First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.

- -Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then an NegativeArraySizeException is thrown.

- -Next, space is allocated for the new array. If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an OutOfMemoryError.

- -Then, if a single DimExpr appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

- -If an array creation expression contains N DimExpr expressions, then it effectively executes a set of nested loops of depth N-1 to create the implied arrays of arrays.

- -

For example, the declaration:

-
float[][] matrix = new float[3][3];
-
-is equivalent in behavior to:

-

float[][] matrix = new float[3][];
-for (int d = 0; d < matrix.length; d++)
-        matrix[d] = new float[3];
-
-and:

-

Age[][][][][] Aquarius = new Age[6][10][8][12][];
-
-is equivalent to:

-

Age[][][][][] Aquarius = new Age[6][][][][];
-for (int d1 = 0; d1 < Aquarius.length; d1++) {
-        Aquarius[d1] = new Age[10][][][];
-        for (int d2 = 0; d2 < Aquarius[d1].length; d2++) {
-                Aquarius[d1][d2] = new Age[8][][];
-                for (int d3 = 0; d3 < Aquarius[d1][d2].length; d3++) {
-                        Aquarius[d1][d2][d3] = new Age[12][];
-                }
-        }
-}
-
-with d, d1, d2 and d3 replaced by names that are not already locally declared. Thus, a single new expression actually creates one array of length 6, 6 arrays of length 10, 6 x 10 = 60 arrays of length 8, and 6 x 10 x 8 = 480 arrays of length 12. This example leaves the fifth dimension, which would be arrays containing the actual array elements (references to Age objects), initialized only to null references. These arrays can be filled in later by other code, such as:

-

Age[] Hair = { new Age("quartz"), new Age("topaz") };
-Aquarius[1][9][6][9] = Hair;
-
- -

A multidimensional array need not have arrays of the same length at each level.

- -

Thus, a triangular matrix may be created by:

-
-float triang[][] = new float[100][];
-for (int i = 0; i < triang.length; i++)
-        triang[i] = new float[i+1];
-
- -

15.10.2 Example: Array Creation Evaluation Order

- -In an array creation expression (§15.10), there may be one or more dimension expressions, each within brackets. Each dimension expression is fully evaluated before any part of any dimension expression to its right.

- -

Thus:

-
class Test {
-        public static void main(String[] args) {
-                int i = 4;
-                int ia[][] = new int[i][i=3];
-                System.out.println(
-                        "[" + ia.length + "," + ia[0].length + "]");
-        }
-}
-
-prints:

-

[4,3]
-
-because the first dimension is calculated as 4 before the second dimension expression sets i to 3.

- -

If evaluation of a dimension expression completes abruptly, no part of any dimension expression to its right will appear to have been evaluated. Thus, the example:

-
class Test {
-        public static void main(String[] args) {
-                int[][] a = { { 00, 01 }, { 10, 11 } };
-                int i = 99;
-                try {
-                        a[val()][i = 1]++;
-                } catch (Exception e) {
-                        System.out.println(e + ", i=" + i);
-                }
-        }
-        static int val() throws Exception {
-                throw new Exception("unimplemented");
-        }
-}
-
-prints:

-

java.lang.Exception: unimplemented, i=99
-
-because the embedded assignment that sets i to 1 is never executed.

- - -

15.10.3 Example: Array Creation and Out-of-Memory Detection

- -If evaluation of an array creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs only after evaluation of all dimension expressions has completed normally.

- -

So, for example, the test program:

-
class Test {
-        public static void main(String[] args) {
-                int len = 0, oldlen = 0;
-                Object[] a = new Object[0];
-                try {
-                        for (;;) {
-                                ++len;
-                                Object[] temp = new Object[oldlen = len];
-                                temp[0] = a;
-                                a = temp;
-                        }
-                } catch (Error e) {
-                        System.out.println(e + ", " + (oldlen==len));
-                }
-        }
-}
-
-prints:

-

java.lang.OutOfMemoryError, true
-
-because the out-of-memory condition is detected after the dimension expression oldlen = len is evaluated.

- -

Compare this to class instance creation expressions (§15.9), which detect the out-of-memory condition before evaluating argument expressions (§15.9.6).

- -

- - -

15.11 Field Access Expressions

- -A field access expression may access a field of an object or array, a reference to which is the value of either an expression or the special keyword super. (It is also possible to refer to a field of the current instance or current class by using a simple name; see §6.5.6.)

-

-
-FieldAccess:
-        Primary . Identifier
-   super . Identifier
-        ClassName .super . Identifier
-        
-
-The meaning of a field access expression is determined using the same rules as for qualified names (§6.6), but limited by the fact that an expression cannot denote a package, class type, or interface type.

- - -

15.11.1 Field Access Using a Primary

- -The type of the Primary must be a reference type T, or a compile-time error occurs. The meaning of the field access expression is determined as follows:

-

-Note, specifically, that only the type of the Primary expression, not the class of the actual object referred to at run time, is used in determining which field to use.

- -

Thus, the example:

- -

-
class S { int x = 0; }
-class T extends S { int x = 1; }
-class Test {
-        public static void main(String[] args) {
-                T t = new T();
-                System.out.println("t.x=" + t.x + when("t", t));
-                S s = new S();
-                System.out.println("s.x=" + s.x + when("s", s));
-                s = t;
-                System.out.println("s.x=" + s.x + when("s", s));
-        }
-
-

-

       static String when(String name, Object t) {
-                return " when " + name + " holds a "
-                        + t.getClass() + " at run time.";
-        }
-}
-
-produces the output:

-

t.x=1 when t holds a class T at run time.
-s.x=0 when s holds a class S at run time.
-s.x=0 when s holds a class T at run time.
-
-The last line shows that, indeed, the field that is accessed does not depend on the run-time class of the referenced object; even if s holds a reference to an object of class T, the expression s.x refers to the x field of class S, because the type of the expression s is S. Objects of class T contain two fields named x, one for class T and one for its superclass S.

- -

This lack of dynamic lookup for field accesses allows programs to be run efficiently with straightforward implementations. The power of late binding and overriding is available, but only when instance methods are used. Consider the same example using instance methods to access the fields:

-
class S { int x = 0; int z() { return x; } }
-class T extends S { int x = 1; int z() { return x; } }
-class Test {
-        public static void main(String[] args) {
-                T t = new T();
-                System.out.println("t.z()=" + t.z() + when("t", t));
-                S s = new S();
-                System.out.println("s.z()=" + s.z() + when("s", s));
-                s = t;
-                System.out.println("s.z()=" + s.z() + when("s", s));
-        }
-        static String when(String name, Object t) {
-                return " when " + name + " holds a "
-                        + t.getClass() + " at run time.";
-        }
-}
-
-Now the output is:

-

t.z()=1 when t holds a class T at run time.
-s.z()=0 when s holds a class S at run time.
-s.z()=1 when s holds a class T at run time.
-
-The last line shows that, indeed, the method that is accessed does depend on the run-time class of referenced object; when s holds a reference to an object of class T, the expression s.z() refers to the z method of class T, despite the fact that the type of the expression s is S. Method z of class T overrides method z of class S.

- -

The following example demonstrates that a null reference may be used to access a class (static) variable without causing an exception:

-
class Test {
-        static String mountain = "Chocorua";
-        static Test favorite(){
-                System.out.print("Mount ");
-                return null;
-        }
-        public static void main(String[] args) {
-                System.out.println(favorite().mountain);
-        }
-}
-
-It compiles, executes, and prints:

-

Mount Chocorua
-
- -

Even though the result of favorite() is null, a NullPointerException is not thrown. That "Mount " is printed demonstrates that the Primary expression is indeed fully evaluated at run time, despite the fact that only its type, not its value, is used to determine which field to access (because the field mountain is static).

- - -

15.11.2 Accessing Superclass Members using super

- -The special forms using the keyword super are valid only in an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class; these are exactly the same situations in which the keyword this may be used (§15.8.3). The forms involving super may not be used anywhere in the class Object, since Object has no superclass; if super appears in class Object, then a compile-time error results.

- -Suppose that a field access expression super.name appears within class C, and the immediate superclass of C is class S. Then super.name is treated exactly as if it had been the expression ((S)this).name; thus, it refers to the field named name of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named name that is visible in class S, even if that field is hidden by a declaration of a field named name in class C.

- -

The use of super is demonstrated by the following example:

-
interface I { int x = 0; }
-class T1 implements I { int x = 1; }
-class T2 extends T1 { int x = 2; }
-class T3 extends T2 {
-        int x = 3;
-        void test() {
-                System.out.println("x=\t\t"+x);
-                System.out.println("super.x=\t\t"+super.x);
-                System.out.println("((T2)this).x=\t"+((T2)this).x);
-                System.out.println("((T1)this).x=\t"+((T1)this).x);
-                System.out.println("((I)this).x=\t"+((I)this).x);
-        }
-}
-
-class Test {
-        public static void main(String[] args) {
-                new T3().test();
-        }
-}
-
-

- -which produces the output:

- -

-

-x=              3
-super.x=        2
-((T2)this).x=   2
-((T1)this).x=   1
-((I)this).x=    0
-
-

- -Within class T3, the expression super.x is treated exactly as if it were:

- -

-

((T2)this).x
-
-
-Suppose that a field access expression T.super.name appears within class C, and the immediate superclass of the class denoted by T is a class whose fully qualified name is S. Then T.super.name is treated exactly as if it had been the expression ((S)T.this).name.

- -Thus the expression T.super.name can access the field named name that is visible in the class named by S, even if that field is hidden by a declaration of a field named name in the class named by T.

- -It is a compile-time error if the current class is not an inner class of class T or T itself.

- - -

- - -

15.12 Method Invocation Expressions

- -A method invocation expression is used to invoke a class or instance method.

-

-
-MethodInvocation:
-        MethodName ( ArgumentListopt )
-        Primary . NonWildTypeArgumentsopt Identifier ( ArgumentListopt )
-        super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt )
-        ClassName . super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt )
-        TypeName . NonWildTypeArguments Identifier ( ArgumentListopt )
-
-The definition of ArgumentList from §15.9 is repeated here for convenience:

-

-
-ArgumentList:
-        Expression
-        ArgumentList , Expression
-        
-
-
-

Resolving a method name at compile time is more complicated than resolving a field name because of the possibility of method overloading. Invoking a method at run time is also more complicated than accessing a field because of the possibility of instance method overriding.

- -Determining the method that will be invoked by a method invocation expression involves several steps. The following three sections describe the compile-time processing of a method invocation; the determination of the type of the method invocation expression is described in §15.12.3.

- - -

15.12.1 Compile-Time Step 1: Determine Class or Interface to Search

- - The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to check for definitions of methods of that name. There are several cases to consider, depending on the form that precedes the left parenthesis, as follows:

-

- -

15.12.2 Compile-Time Step 2: Determine Method Signature

- -The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments. There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

- -A method is applicable if it is either applicable by subtyping (§15.12.2.2), applicable by method invocation conversion (§15.12.2.3), or it is an applicable variable arity method (§15.12.2.4).

- -The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1). The remainder of the process is split into three phases.

- -


-

-Discussion -

-

- The purpose of the division into phases is to ensure compatibility with older versions of the Java programming language.

-


- -

- -The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

- -


-

-Discussion -

-

- This guarantees that any calls that were valid in older versions of the language are not considered ambiguous as a result of the introduction of variable arity methods, implicit boxing and/or unboxing.

-


- -

- -The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

-


-

-Discussion -

-

- - This ensures that a variable arity method is never invoked if an applicable fixed arity method exists.

-


- -

- -The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing and unboxing.

- -Deciding whether a method is applicable will, in the case of generic methods (§8.4.4), require that actual type arguments be determined. Actual type arguments may be passed explicitly or implicitly. If they are passed implicitly, they must be inferred (§15.12.2.7) from the types of the argument expressions.

- -If several applicable methods have been identified during one of the three phases of applicability testing, then the most specific one is chosen, as specified in section §15.12.2.5. See the following subsections for details.

- -

- - -

15.12.2.1 Identify Potentially Applicable Methods

- -A member method is potentially applicable to a method invocation if and only if all of the following are true:

-

-

-


-

- Discussion -

-

- - The clause above implies that a non-generic method may be potentially applicable to an invocation that supplies explicit type parameters. Indeed, it may turn out to be applicable. In such a case, the type parameters will simply be ignored.

- -This rule stems from issues of compatibility and principles of substitutability. Since interfaces or superclasses may be generified independently of their subtypes, we may override a generic method with a non-generic one. However, the overriding (non-generic) method must be applicable to calls to the generic method, including calls that explicitly pass type parameters. Otherwise the subtype would not be substitutable for its generified supertype.

-


- -

- -Whether a member method is accessible at a method invocation depends on the access modifier (public, none, protected, or private) in the member's declaration and on where the method invocation appears.

- -The class or interface determined by compile-time step 1 (§15.12.1) is searched for all member methods that are potentially applicable to this method invocation; members inherited from superclasses and superinterfaces are included in this search.

- -In addition, if the method invocation has, before the left parenthesis, a MethodName of the form Identifier, then the search process also examines all methods that are (a) imported by single-static-import declarations (§7.5.3) and static-import-on-demand declarations (§7.5.4) within the compilation unit (§7.3) within which the method invocation occurs, and (b) not shadowed (§6.3.1) at the place where the method invocation appears.

- -If the search does not yield at least one method that is potentially applicable, then a compile-time error occurs.

- -

- - - -

15.12.2.2 Phase 1: Identify Matching Arity Methods Applicable by Subtyping

- -Let m be a potentially applicable method (§15.12.2.1), let e1, ..., en be the actual argument expressions of the method invocation and let Ai be the type of ei, 1in. Then:

-

-The method m is applicable by subtyping if and only if both of the following conditions hold:

-

-If no method applicable by subtyping is found, the search for applicable methods continues with phase 2 (§15.12.2.3). Otherwise, the most specific method (§15.12.2.5) is chosen among the methods that are applicable by subtyping.

- - -

15.12.2.3 Phase 2: Identify Matching Arity Methods Applicable by Method Invocation Conversion

- -Let m be a potentially applicable method (§15.12.2.1), let e1, ..., en be the actual argument expressions of the method invocation and let Ai be the type of ei, 1in. Then:

-

-The method m is applicable by method invocation conversion if and only if both of the following conditions hold:

-

-If no method applicable by method invocation conversion is found, the search for applicable methods continues with phase 3 (§15.12.2.4). Otherwise, the most specific method (§15.12.2.5) is chosen among the methods that are applicable by method invocation conversion.

- - -

15.12.2.4 Phase 3: Identify Applicable Variable Arity Methods

- -Let m be a potentially applicable method (§15.12.2.1) with variable arity, let e1, ..., ek be the actual argument expressions of the method invocation and let Ai be the type of ei, 1ik. Then:

-

-The method m is an applicable variable-arity method if and only if all three of the following conditions hold:

-

-If no applicable variable arity method is found, a compile-time error occurs. Otherwise, the most specific method (§15.12.2.5) is chosen among the applicable variable-arity methods.

- -

- - -

15.12.2.5 Choosing the Most Specific Method

- -If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

- -

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

- -One fixed-arity member method named m is more specific than another member method of the same name and arity if all of the following conditions hold:

-

-In addition, one variable arity member method named m is more specific than another variable arity member method of the same name if either:

-

-The above conditions are the only circumstances under which one method may be more specific than another.

- -A method m1 is strictly more specific than another method m2 if and only if m1 is more specific than m2 and m2 is not more specific than m1.

- -A method is said to be maximally specific for a method invocation if it is accessible and applicable and there is no other method that is applicable and accessible that is strictly more specific.

- -If there is exactly one maximally specific method, then that method is in fact the most specific method; it is necessarily more specific than any other accessible method that is applicable. It is then subjected to some further compile-time checks as described in §15.12.3.

- -It is possible that no method is the most specific, because there are two or more methods that are maximally specific. In this case:

-

-

- -

- -

- - -

15.12.2.6 Method Result and Throws Types

- -The exception types of the throws clause of the chosen method are determined as follows:

-

-A method invocation expression can throw an exception type E iff either:

-

-

- - -

15.12.2.7 Inferring Type Arguments Based on Actual Arguments

- -In this section, we describe the process of inferring type arguments for method and constructor invocations. This process is invoked as a subroutine when testing for method (or constructor) applicability (§15.12.2.2 - §15.12.2.4).

- -


-

- Discussion -

-

- - The process of type inference is inherently complex. Therefore, it is useful to give an informal overview of the process before delving into the detailed specification.

- -Inference begins with an initial set of constraints. Generally, the constraints require that the statically known types of the actual arguments are acceptable given the declared formal argument types. We discuss the meaning of "acceptable" below.

- -Given these initial constraints, one may derive a set of supertype and/or equality constraints on the formal type parameters of the method or constructor.

- -Next, one must try and find a solution that satisfies the constraints on the type parameters. As a first approximation, if a type parameter is constrained by an equality constraint, then that constraint gives its solution. Bear in mind that the constraint may equate one type parameter with another, and only when the entire set of constraints on all type variables is resolved will we have a solution.

- -A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection.

- -Computing the intersection is more complicated than one might first realize. Given that a type parameter is constrained to be a supertype of two distinct invocations of a generic type, say List<Object> and List<String>, the naive intersection operation might yield Object. However, a more sophisticated analysis yields a set containing List<?>. Similarly, if a type parameter, T, is constrained to be a supertype of two unrelated interfaces I and J, we might infer T must be Object, or we might obtain a tighter bound of I & J. These issues are discussed in more detail later in this section.

-


- -

- -We will use the following notational conventions in this section:

-

-Inference begins with a set of initial constraints of the form A << F, A = F, or A >> F, where U << V indicates that type U is convertible to type V by method invocation conversion (§5.3), and U >> V indicates that type V is convertible to type U by method invocation conversion.

- -


-

Discussion -

-

- -In a simpler world, the constraints could be of the form A <: F - simply requiring that the actual argument types be subtypes of the formal ones. However, reality is more involved. As discussed earlier, method applicability testing consists of up to three phases; this is required for compatibility reasons. Each phase imposes slightly different constraints. If a method is applicable by subtyping (§15.12.2.2), the constraints are indeed subtyping constraints. If a method is applicable by method invocation conversion (§15.12.2.3), the constraints imply that the actual type is convertible to the formal type by method invocation conversion. The situation is similar for the third phase (§15.12.2.4), but the exact form of the constraints differ due to the variable arity.

-


- -

- -These constraints are then reduced to a set of simpler constraints of the forms T :> X, T = X or T <: X, where T is a type parameter of the method. This reduction is achieved by the procedure given below:

- -


-

- Discussion -

-

- - It may be that the initial constraints are unsatisfiable; we say that inference is overconstrained. In that case, we do not necessarily derive unsatisfiable constraints on the type parameters. Instead, we may infer actual type arguments for the invocation, but once we substitute the actual type arguments for the formal type parameters, the applicability test may fail because the actual argument types are not acceptable given the substituted formals.

- -An alternative strategy would be to have type inference itself fail in such cases. Compilers may choose to do so, provided the effect is equivalent to that specified here.

-


- -

- -Given a constraint of the form A << F, A = F, or A >> F:

-

- -

-


-

- Discussion -

-

- - This follows from the covariant subtype relation among array types. The constraint A << F, in this case means that A << U[]. A is therefore necessarily an array type V[], or a type variable whose upper bound is an array type V[] - otherwise the relation A << U[] could never hold true. It follows that V[] << U[]. Since array subtyping is covariant, it must be the case that V << U.

-


- - - -

-


-

- Discussion -

-

- - For simplicity, assume that G takes a single type argument. If the method invocation being examined is to be applicable, it must be the case that A is a subtype of some invocation of G. Otherwise, A << F would never be true.

-In other words, A << F, where F = G<U>, implies that A << G<V> for some V. Now, since U is a type expression (and therefore, U is not a wildcard type argument), it must be the case that U = V, by the non-variance of ordinary parameterized type invocations.

- -The formulation above merely generalizes this reasoning to generics with an arbitrary number of type arguments.

-


- -

-


-

- Discussion -

-

- - Again, let's keep things as simple as possible, and consider only the case where G has a single type argument.

-A <<F in this case means A << G<? extends U>. As above, it must be the case that A is a subtype of some invocation of G. However, A may now be a subtype of either G<V>, or G<? extends V>, or G<? super V>. We examine these cases in turn. The first variation is described (generalized to multiple arguments) by the sub-bullet directly above. We therefore have A = G<V> << G<? extends U>. The rules of subtyping for wildcards imply that V << U.

-


- -

-

-

-


-

-Discussion -

-

-Extending the analysis above, we have A = G<? extends V> << G<? extends U>. The rules of subtyping for wildcards again imply that V << U.

-


- -

-

-

-


-

-Discussion -

-Here, we have A = G<? super V> << G<? extends U>. In general, we cannot conclude anything in this case. However, it is not necessarily an error. It may be that U will eventually be inferred to be Object, in which case the call may indeed be valid. Therefore, we simply refrain from placing any constraint on U.

-


- -

-

-

-


-

- Discussion -

-

- - As usual, we consider only the case where G has a single type argument.

-A <<F in this case means A << G<? super U>. As above, it must be the case that A is a subtype of some invocation of G. A may now be a subtype of either G<V>, or G<? extends V>, or G<? super V>. We examine these cases in turn. The first variation is described (generalized to multiple arguments) by the sub-bullet directly above. We therefore have A = G<V> << G<? super U>. The rules of subtyping for wildcards imply that V >> U.

-


- -

-

-
-

-Discussion -

-

-We have A = G<? super V> << G<? super U>. The rules of subtyping for lower-bounded wildcards again imply that V >> U.

-


- -

-

-
-

-Discussion -

-

-Here, we have A = G<? extends V> << G<? super U>. In general, we cannot conclude anything in this case. However, it is not necessarily an error. It may be that U will eventually be inferred to the null type, in which case the call may indeed be valid. Therefore, we simply refrain from placing any constraint on U.

- -


-

-

-
-

-Discussion -

-

-Such a constraint is never part of the initial constraints. However, it can arise as the algorithm recurses. We have seen this occur above, when the constraint A << F relates two parameterized types, as in G<V> << G<U>.

-


- -

-

-
-

-Discussion -

-

-Clearly, if the array types U[] and V[] are the same, their component types must be the same.

-


- -

-

- -

-


-

-Discussion -

-

- - Such situations arise when the algorithm recurses, due to the contravariant subtyping rules associated with lower-bounded wildcards (those of the form G<? super X>).

-It might be tempting to consider A>> F as being the same as F << A, but the problem of inference is not symmetric. We need to remember which participant in the relation includes a type to be inferred.

-


- -

-

-

-


-

- Discussion -

-

- - We do not make use of such constraints in the main body of the inference algorithm. However, they are used in section §15.12.2.8.

-


- -

-

- -

-


-

- Discussion -

-

- - This follows from the covariant subtype relation among array types. The constraint A >> F, in this case means that A >> U[]. A is therefore necessarily an array type V[], or a type variable whose upper bound is an array type V[] - otherwise the relation A >> U[] could never hold true. It follows that V[] >> U[]. Since array subtyping is covariant, it must be the case that V >> U.

-


- - -

- -


-

-Discussion -

-

- In this case (once again restricting the analysis to the unary case), we have the constraint A >> F = G<U>. A must be a supertype of the generic type G. However, since A is not a parameterized type, it cannot depend upon the type argument U in any way. It is a supertype of G<X> for every X that is a valid type argument to G. No meaningful constraint on U can be derived from A.

- -


- -

-


-

- Discussion -

-

- - Our goal here is to simplify the relationship between A and F. We aim to recursively invoke the algorithm on a simpler case, where the actual type argument is known to be an invocation of the same generic type declaration as the formal.

-Let's consider the case where both H and G have only a single type argument. Since we have the constraint A = H<X> >> F = G<U>, where H is distinct from G, it must be the case that H is some proper superclass or superinterface of G. There must be a (non-wildcard) invocation of H that is a supertype of F = G<U>. Call this invocation V.

- -If we replace F by V in the constraint, we will have accomplished the goal of relating two invocations of the same generic (as it happens, H).

- -How do we compute V? The declaration of G must introduce a formal type parameter S, and there must be some (non-wildcard) invocation of H, H<U1>, that is a supertype of G<S>. Substituting the type expression U for S will then yield a (non-wildcard) invocation of H, H<U1>[S = U], that is a supertype of G<U>. For example, in the simplest instance, U1 might be S, in which case we have G<S> <: H<S>, and G<U> <: H<U> = H<S>[S = U] = V.

- -It may be the case that H<U1> is independent of S - that is, S does not occur in U1 at all. However, the substitution described above is still valid - in this situation, V = H<U1>[S = U] = H<U1>. Furthermore, in this circumstance, G<T> <: H<U1> for any T, and in particular G<U> <: H<U1> = V.

- -Regardless of whether U1 depends on S, we have determined the type V, the invocation of H that is a supertype of G<U>. We can now invoke the algorithm recursively on the constraint H<X> = A >> V = H<U1>[S = U]. We will then be able to relate the type arguments of both invocations of H and extract the relevant constraints from them.

-


- -

-

- -
-

-Discussion -

-

- We have A = G<W> >> F = G<U> for some type expression W. Since W is a type expression (and not a wildcard type argument), it must be the case that W = U, by the non-variance of parameterized types.

-


- -

-

-

-


-

- Discussion -

-

- - We have A = G<? extends W> >> F = G<U> for some type expression W. It must be the case that W >> U, by the subtyping rules for wildcard types.

-


- -

-

-

-


- Discussion -

-

- - We have A = G<? super W> >> F = G<U> for some type expression W. It must be the case that W << U, by the subtyping rules for wildcard types.

-


- -

-


-

- Discussion -

-

- - Once again restricting the analysis to the unary case, we have the constraint A >> F = G<? extends U>. A must be a supertype of the generic type G. However, since A is not a parameterized type, it cannot depend upon U in any way. It is a supertype of the type G<? extends X> for every X such that ? extends X is a valid type argument to G. No meaningful constraint on U can be derived from A.

-


- - -

-


- -

-Discussion -

- -

- - Our goal here is once more to simplify the relationship between A and F, and recursively invoke the algorithm on a simpler case, where the actual type argument is known to be an invocation of the same generic type as the formal.

- -Assume both H and G have only a single type argument. Since we have the constraint A = H<X> >> F = G<? extends U>, where H is distinct from G, it must be the case that H is some proper superclass or superinterface of G. There must be an invocation of H<Y> such that H<X> >> H<Y> that we can use instead of F = G<? extends U>.

- -How do we compute H<Y>? As before, note that the declaration of G must introduce a formal type parameter S, and there must be some (non-wildcard) invocation of H, H<U1>, that is a supertype of G<S>. However, substituting ? extends U for S is not generally valid. To see this, assume U1 = T[].

- -Instead, we produce an invocation of H, H<? extends U1>[S = U]. In the simplest instance, U1 might be S, in which case we have G<S> <: H<S>, and G<? extends U> <: H<? extends U> = H<? extends S>[S = U] = V.

-


- -

-

- -

-


-

- Discussion -

-

- - We have A = G<? extends W> >> F = G<? extends U> for some type expression W. By the subtyping rules for wildcards it must be the case that W >> U.

-


- -

-

-

-


- -

- Discussion -

-

- - Restricting the analysis to the unary case, we have the constraint A >> F = G<? super U>. A must be a supertype of the generic type G. However, since A is not a parameterized type, it cannot depend upon U in any way. It is a supertype of the type G<? super X> for every X such that ? super X is a valid type argument to G. No meaningful constraint on U can be derived from A.

-


- -

-


-

- Discussion -

-

- - The treatment here is analogous to the case where A = G<? extends U>. Here our example would produce an invocation H<? super U1>[S = U]

-


- -

-

- -

-


-

- Discussion -

-

- - We have A = G<? super W> >> F = G<? super U> for some type expression W. It must be the case that W << U, by the subtyping rules for wildcard types.

-


- -

-


-

- Discussion -

-

- - This concludes the process of determining constraints on the formal type parameters of a method. -

-Note that this process does not impose any constraints on the type parameters based on their declared bounds. Once the actual type arguments are inferred, they will be tested against the declared bounds of the formal type parameters as part of applicability testing.

- -Note also that type inference does not affect soundness in any way. If the types inferred are nonsensical, the invocation will yield a type error. The type inference algorithm should be viewed as a heuristic, designed to perfdorm well in practice. If it fails to infer the desired result, explicit type paramneters may be used instead.

-


- -

- -Next, for each type variable Tj, 1jn, the implied equality constraints are resolved as follows:

- -For each implied equality constraint Tj = U or U = Tj:

-

- Then, for each remaining type variable Tj, the constraints Tj :> U are considered. Given that these constraints are Tj :> U1 ... Tj :> Uk, the type of Tj is inferred as lub(U1 ... Uk), computed as follows:

- -For a type U, we write ST(U) for the set of supertypes of U, and define the erased supertype set of U,

- -EST(U) = { V | W in ST(U) and V = |W| }

- - where |W| is the erasure (§4.6) of W.

-


- -

- Discussion -

-

- - The reason for computing the set of erased supertypes is to deal with situations where a type variable is constrained to be a supertype of several distinct invocations of a generic type declaration, For example, if T :> List<String> and T :> List<Object>, simply intersecting the sets ST(List<String>) = {List<String>, Collection<String>, Object} and ST(List<Object>) = {List<Object>), Collection<Object>, Object} would yield a set {Object}, and we would have lost track of the fact that T can safely be assumed to be a List.

- -In contrast, intersecting EST(List<String>) = {List, Collection, Object} and EST(List<Object>) = {List, Collection, Object} yields {List, Collection, Object}, which we will eventually enable us to infer T = List<?> as described below.

-


- -

- -The erased candidate set for type parameter Tj , EC, is the intersection of all the sets EST(U) for each U in U1 .. Uk. The minimal erased candidate set for Tj is - -MEC = { V | V in EC, and for all WV in EC, it is not the case that W <: V}

-


- -

-Discussion -

- -

- - Because we are seeking to infer more precise types, we wish to filter out any candidates that are supertypes of other candidates. This is what computing MEC accomplishes.

- -In our running example, we had EC = {List, Collection, Object}, and now MEC = {List}.

- -The next step will be to recover actual type arguments for the inferred types.

-


- -

- - For any element G of MEC that is a generic type declaration, define the relevant invocations of G, Inv(G) to be:

- -Inv(G) = { V | 1ik, V in ST(Ui), V = G<...>}

- -


-

- Discussion -

-

- - In our running example, the only generic element of MEC is List, and Inv(List) = {List<String>, List<Object>}. We now will seek to find a type argument for List that contains (§4.5.1.1) both String and Object.

- -This is done by means of the least containing invocation (lci) operation defined below. The first line defines lci() on a set, such as Inv(List), as an operation on a list of the elements of the set. The next line defines the operation on such lists, as a pairwise reduction on the elements of the list. The third line is the definition of lci() on pairs of parameterized types, which in turn relies on the notion of least containing type argument (lcta).

- -lcta() is defined for all six possible cases. Then CandidateInvocation(G) defines the most specific invocation of the generic G that is contains all the invocations of G that are known to be supertypes of Tj. This will be our candidate invocation of G in the bound we infer for Tj .

-


- -

- -and let CandidateInvocation(G) = lci(Inv(G)) where lci, the least containing invocation is defined

- -lci(S) = lci(e1, ..., en) where ei in S, 1in
- -lci(e1, ..., en) = lci(lci(e1, e2), e3, ..., en)
- -lci(G<X1, ..., Xn>, G<Y1, ..., Yn>) = G<lcta(X1, Y1),..., lcta(Xn, Yn)>

- -where lcta() is the the least containing type argument function defined (assuming U and V are type expressions) as:

- -lcta(U, V) = U if U = V, ? extends lub(U, V) otherwise
- -lcta(U, ? extends V) = ? extends lub(U, V)
- -lcta(U, ? super V) = ? super glb(U, V)
- -lcta(? extends U, ? extends V) = ? extends lub(U, V)
- -lcta(? extends U, ? super V) = U if U = V, ? otherwise
- -lcta(? super U, ? super V) = ? super glb(U, V)

- -

- -where glb() is as defined in (§5.1.10).

-


- -

- Discussion -

-

- - Finally, we define a bound for Tj based on on all the elements of the minimal erased candidate set of its supertypes. If any of these elements are generic, we use the CandidateInvocation() function to recover the type argument information.

-


- -

- -Then, define Candidate(W) = CandidateInvocation(W) if W is generic, W otherwise.

- - Then the inferred type for Tj is - -lub(U1 ... Uk) = Candidate(W1) & ... & Candidate(Wr) where Wi, 1ir, are the elements of MEC.

- -It is possible that the process above yields an infinite type. This is permissible, and Java compilers must recognize such situations and represent them appropriately using cyclic data structures.

- -


-

- Discussion -

-

- - The possibility of an infinite type stems from the recursive calls to lub().

- -Readers familiar with recursive types should note that an infinite type is not the same as a recursive type.

-


- -

- - -

15.12.2.8 Inferring Unresolved Type Arguments

- -If any of the method's type arguments were not inferred from the types of the actual arguments, they are now inferred as follows.

-

-Then, a set of initial constraints consisting of:

-

-is created and used to infer constraints on the type arguments using the algorithm of section (§15.12.2.7). Any equality constraints are resolved, and then, for each remaining constraint of the form Ti <: Uk, the argument Ti is inferred to be glb(U1, ..., Uk) (§5.1.10).

- -Any remaining type variables that have not yet been inferred are then inferred to have type Object

-

- -

15.12.2.9 Examples

- -

In the example program:

-
public class Doubler {
-        static int two() { return two(1); }
-        private static int two(int i) { return 2*i; }
-}
-class Test extends Doubler {
-        public static long two(long j) {return j+j; }
-        public static void main(String[] args) {
-                System.out.println(two(3));
-                System.out.println(Doubler.two(3)); // compile-time error
-        }
-}
-
-for the method invocation two(1) within class Doubler, there are two accessible methods named two, but only the second one is applicable, and so that is the one invoked at run time. For the method invocation two(3) within class Test, there are two applicable methods, but only the one in class Test is accessible, and so that is the one to be invoked at run time (the argument 3 is converted to type long). For the method invocation Doubler.two(3), the class Doubler, not class Test, is searched for methods named two; the only applicable method is not accessible, and so this method invocation causes a compile-time error.

- -

Another example is:

-
class ColoredPoint {
-        int x, y;
-        byte color;
-        void setColor(byte color) { this.color = color; }
-}
-class Test {
-        public static void main(String[] args) {
-                ColoredPoint cp = new ColoredPoint();
-                byte color = 37;
-                cp.setColor(color);
-                cp.setColor(37);        // compile-time error
-        }
-}
-
-Here, a compile-time error occurs for the second invocation of setColor, because no applicable method can be found at compile time. The type of the literal 37 is int, and int cannot be converted to byte by method invocation conversion. Assignment conversion, which is used in the initialization of the variable color, performs an implicit conversion of the constant from type int to byte, which is permitted because the value 37 is small enough to be represented in type byte; but such a conversion is not allowed for method invocation conversion.

- -

If the method setColor had, however, been declared to take an int instead of a byte, then both method invocations would be correct; the first invocation would be allowed because method invocation conversion does permit a widening conversion from byte to int. However, a narrowing cast would then be required in the body of setColor:

-
       void setColor(int color) { this.color = (byte)color; }
-
- -

15.12.2.10 Example: Overloading Ambiguity

- -Consider the example:

-

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-
-class Test {
-        static void test(ColoredPoint p, Point q) {
-                System.out.println("(ColoredPoint, Point)");
-        }
-        static void test(Point p, ColoredPoint q) {
-                System.out.println("(Point, ColoredPoint)");
-        }
-        public static void main(String[] args) {
-                ColoredPoint cp = new ColoredPoint();
-                test(cp, cp);                                                                                   // compile-time error
-        }
-}
-
-This example produces an error at compile time. The problem is that there are two declarations of test that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous.

- -

If a third definition of test were added:

-
       static void test(ColoredPoint p, ColoredPoint q) {
-                System.out.println("(ColoredPoint, ColoredPoint)");
-        }
-
-then it would be more specific than the other two, and the method invocation would no longer be ambiguous.

- - -

15.12.2.11 Example: Return Type Not Considered

- -As another example, consider:

-

class Point { int x, y; }
-class ColoredPoint extends Point { int color; }
-class Test {
-        static int test(ColoredPoint p) {
-                return p.color;
-        }
-        static String test(Point p) {
-                return "Point";
-        }
-        public static void main(String[] args) {
-                ColoredPoint cp = new ColoredPoint();
-                String s = test(cp);                                                                                    // compile-time error
-        }
-}
-
-Here the most specific declaration of method test is the one taking a parameter of type ColoredPoint. Because the result type of the method is int, a compile-time error occurs because an int cannot be converted to a String by assignment conversion. This example shows that the result types of methods do not participate in resolving overloaded methods, so that the second test method, which returns a String, is not chosen, even though it has a result type that would allow the example program to compile without error.

- - -

15.12.2.12 Example: Compile-Time Resolution

- -The most applicable method is chosen at compile time; its descriptor determines what method is actually executed at run time. If a new method is added to a class, then source code that was compiled with the old definition of the class might not use the new method, even if a recompilation would cause this method to be chosen.

- -

So, for example, consider two compilation units, one for class Point:

-
package points;
-public class Point {
-        public int x, y;
-        public Point(int x, int y) { this.x = x; this.y = y; }
-        public String toString() { return toString(""); }
-        public String toString(String s) {
-                return "(" + x + "," + y + s + ")";
-        }
-}
-
-and one for class ColoredPoint:

-

package points;
-public class ColoredPoint extends Point {
-        public static final int
-                RED = 0, GREEN = 1, BLUE = 2;
-        public static String[] COLORS =
-                { "red", "green", "blue" };
-        public byte color;
-        public ColoredPoint(int x, int y, int color) {
-                super(x, y); this.color = (byte)color;
-        }
-        /** Copy all relevant fields of the argument into
-                    this ColoredPoint object. */
-        public void adopt(Point p) { x = p.x; y = p.y; }
-        public String toString() {
-                String s = "," + COLORS[color];
-                return super.toString(s);
-        }
-}
-
-Now consider a third compilation unit that uses ColoredPoint:

-

import points.*;
-class Test {
-        public static void main(String[] args) {
-                ColoredPoint cp =
-                        new ColoredPoint(6, 6, ColoredPoint.RED);
-                ColoredPoint cp2 =
-                        new ColoredPoint(3, 3, ColoredPoint.GREEN);
-                cp.adopt(cp2);
-                System.out.println("cp: " + cp);
-        }
-}
-
-The output is:

-

cp: (3,3,red)
-
- -

The application programmer who coded class Test has expected to see the word green, because the actual argument, a ColoredPoint, has a color field, and color would seem to be a "relevant field" (of course, the documentation for the package Points ought to have been much more precise!).

- -

Notice, by the way, that the most specific method (indeed, the only applicable method) for the method invocation of adopt has a signature that indicates a method of one parameter, and the parameter is of type Point. This signature becomes part of the binary representation of class Test produced by the compiler and is used by the method invocation at run time.

- -

Suppose the programmer reported this software error and the maintainer of the points package decided, after due deliberation, to correct it by adding a method to class ColoredPoint:

-
-public void adopt(ColoredPoint p) {
-        adopt((Point)p); color = p.color;
-}
-
- -

If the application programmer then runs the old binary file for Test with the new binary file for ColoredPoint, the output is still:

-cp: (3,3,red) - -because the old binary file for Test still has the descriptor "one parameter, whose type is Point; void" associated with the method call cp.adopt(cp2). If the source code for Test is recompiled, the compiler will then discover that there are now two applicable adopt methods, and that the signature for the more specific one is "one parameter, whose type is ColoredPoint; void"; running the program will then produce the desired output:

-

cp: (3,3,green)
-
- -

With forethought about such problems, the maintainer of the points package could fix the ColoredPoint class to work with both newly compiled and old code, by adding defensive code to the old adopt method for the sake of old code that still invokes it on ColoredPoint arguments:

-
-public void adopt(Point p) {
-        if (p instanceof ColoredPoint)
-                color = ((ColoredPoint)p).color;
-        x = p.x; y = p.y;
-}
-
- -

Ideally, source code should be recompiled whenever code that it depends on is changed. However, in an environment where different classes are maintained by different organizations, this is not always feasible. Defensive programming with careful attention to the problems of class evolution can make upgraded code much more robust. See §13 for a detailed discussion of binary compatibility and type evolution.

- - -

15.12.3 Compile-Time Step 3: Is the Chosen Method Appropriate?

- -If there is a most specific method declaration for a method invocation, it is called the compile-time declaration for the method invocation. Three further checks must be made on the compile-time declaration:

-

-The following compile-time information is then associated with the method invocation for use at run time:

-

-If the compile-time declaration for the method invocation is not void, then the type of the method invocation expression is the result type specified in the compile-time declaration.

- - -

15.12.4 Runtime Evaluation of Method Invocation

- -At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

- - -

15.12.4.1 Compute Target Reference (If Necessary)

- -There are several cases to consider, depending on which of the five productions for MethodInvocation (§15.12) is involved:

-

- -

15.12.4.2 Evaluate Arguments

- -The process of evaluating of the argument list differs, depending on whether the method being invoked is a fixed arity method or a variable arity method (§8.4.1).

- -If the method being invoked is a variable arity method (§8.4.1) m, it necessarily has n>0 formal parameters. The final formal parameter of m necessarily has type T[] for some T, and m is necessarily being invoked with k0 actual argument expressions.

- -If m is being invoked with kn actual argument expressions, or, if m is being invoked with k=n actual argument expressions and the type of the kth argument expression is not assignment compatible with T[], then the argument list (e1, ... , en-1, en, ...ek) is evaluated as if it were written as (e1, ..., en-1, new T[]{en, ..., ek}).

- -The argument expressions (possibly rewritten as described above) are now evaluated to yield argument values. Each argument value corresponds to exactly one of the method's n formal parameters.

- -The argument expressions, if any, are evaluated in order, from left to right. If the evaluation of any argument expression completes abruptly, then no part of any argument expression to its right appears to have been evaluated, and the method invocation completes abruptly for the same reason.The result of evaluating the jth argument expression is the jth argument value, for 1jn. Evaluation then continues, using the argument values, as described below.

- - -

15.12.4.3 Check Accessibility of Type and Method

- -Let C be the class containing the method invocation, and let T be the qualifying type of the method invocation (§13.1), and m be the name of the method, as determined at compile time (§15.12.3). An implementation of the Java programming language must insure, as part of linkage, that the method m still exists in the type T. If this is not true, then a NoSuchMethodError (which is a subclass of IncompatibleClassChangeError) occurs. If the invocation mode is interface, then the implementation must also check that the target reference type still implements the specified interface. If the target reference type does not still implement the interface, then an IncompatibleClassChangeError occurs.

- -The implementation must also insure, during linkage, that the type T and the method m are accessible. For the type T:

-

-For the method m:

-

-If either T or m is not accessible, then an IllegalAccessError occurs (§12.3).

- - -

15.12.4.4 Locate Method to Invoke

- -The strategy for method lookup depends on the invocation mode.

- -If the invocation mode is static, no target reference is needed and overriding is not allowed. Method m of class T is the one to be invoked.

- -Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is null, a NullPointerException is thrown at this point. Otherwise, the target reference is said to refer to a target object and will be used as the value of the keyword this in the invoked method. The other four possibilities for the invocation mode are then considered.

- -If the invocation mode is nonvirtual, overriding is not allowed. Method m of class T is the one to be invoked.

- -Otherwise, the invocation mode is interface, virtual, or super, and overriding may occur. A dynamic method lookup is used. The dynamic lookup process starts from a class S, determined as follows:

-

-The dynamic method lookup uses the following procedure to search class S, and then the superclasses of class S, as necessary, for method m.

- -Let X be the compile-time type of the target reference of the method invocation.

-

    - -
  1. If class S contains a declaration for a non-abstract method named m with the same descriptor (same number of parameters, the same parameter types, and the same return type) required by the method invocation as determined at compile time (§15.12.3), then: -
      - -
    • If the invocation mode is super or interface, then this is the method to be invoked, and the procedure terminates. - -
    • If the invocation mode is virtual, and the declaration in S overrides (§8.4.8.1) X.m, then the method declared in S is the method to be invoked, and the procedure terminates. -
    - -
  2. Otherwise, if S has a superclass, this same lookup procedure is performed recursively using the direct superclass of S in place of S; the method to be invoked is the result of the recursive invocation of this lookup procedure. - -
-

The above procedure will always find a non-abstract, accessible method to invoke, provided that all classes and interfaces in the program have been consistently compiled. However, if this is not the case, then various errors may occur. The specification of the behavior of a Java virtual machine under these circumstances is given by The Java Virtual Machine Specification.We note that the dynamic lookup process, while described here explicitly, will often be implemented implicitly, for example as a side-effect of the construction and use of per-class method dispatch tables, or the construction of other per-class structures used for efficient dispatch.

- - -

15.12.4.5 Create Frame, Synchronize, Transfer Control

- -A method m in some class S has been identified as the one to be invoked.

- -Now a new activation frame is created, containing the target reference (if any) and the argument values (if any), as well as enough space for the local variables and stack for the method to be invoked and any other bookkeeping information that may be required by the implementation (stack pointer, program counter, reference to previous activation frame, and the like). If there is not sufficient memory available to create such an activation frame, an StackOverflowError is thrown.

- -The newly created activation frame becomes the current activation frame. The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method, and to make the target reference available as this, if there is a target reference. Before each argument value is assigned to its corresponding parameter variable, it is subjected to method invocation conversion (§5.3), which includes any required value set conversion (§5.1.13).

- -If the erasure of the type of the method being invoked differs in its signature from the erasure of the type of the compile-time declaration for the method invocation (§15.12.3), then if any of the argument values is an object which is not an instance of a subclass or subinterface of the erasure of the corresponding formal parameter type in the compile-time declaration for the method invocation, then a ClassCastException is thrown.

- -


-

- Discussion -

-

- - As an example of such a situation, consider the declarations:

-

class C<T> { abstract T id(T x); }
-class D extends C<String> { String id(String x) { return x; } }
-
-Now, given an invocation

-

C c = new D();
-c.id(new Object()); // fails with a ClassCastException
-
-The erasure of the actual method being invoked, , differs in its signature from that of the compile-time method declaration, C.id(). The former takes an argument of type String while the latter takes an argument of type Object. The invocation fails with a ClassCastException before the body of the method is executed.

- -Such situations can only arise if the program gives rise to an unchecked warning (§5.1.9).

- -Implementations can enforce these semantics by creating bridge methods. In the above example, the following bridge method would be created in class D:

-

Object id(Object x) { return id((String) x); }
-
-This is the method that would actually be invoked by the Java virtual machine in response to the call c.id(new Object()) shown above, and it will execute the cast and fail, as required.

-


- -

- -If the method m is a native method but the necessary native, implementation-dependent binary code has not been loaded or otherwise cannot be dynamically linked, then an UnsatisfiedLinkError is thrown.

- -If the method m is not synchronized, control is transferred to the body of the method m to be invoked.

- -If the method m is synchronized, then an object must be locked before the transfer of control. No further progress can be made until the current thread can obtain the lock. If there is a target reference, then the target must be locked; otherwise the Class object for class S, the class of the method m, must be locked. Control is then transferred to the body of the method m to be invoked. The object is automatically unlocked when execution of the body of the method has completed, whether normally or abruptly. The locking and unlocking behavior is exactly as if the body of the method were embedded in a synchronized statement (§14.19).

- -

- - -

15.12.4.6 Example: Target Reference and Static Methods

- -When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:

-

class Test {
-        static void mountain() {
-                System.out.println("Monadnock");
-        }
-        static Test favorite(){
-                System.out.print("Mount ");
-                return null;
-        }
-        public static void main(String[] args) {
-                favorite().mountain();
-        }
-}
-
-which prints:

-

Mount Monadnock
-
-Here favorite returns null, yet no NullPointerException is thrown.

- - -

15.12.4.7 Example: Evaluation Order

- -As part of an instance method invocation (§15.12), there is an expression that denotes the object to be invoked. This expression appears to be fully evaluated before any part of any argument expression to the method invocation is evaluated.

- -

So, for example, in:

-
class Test {
-        public static void main(String[] args) {
-                String s = "one";
-                if (s.startsWith(s = "two"))
-                        System.out.println("oops");
-        }
-}
-
-the occurrence of s before ".startsWith" is evaluated first, before the argument expression s="two". Therefore, a reference to the string "one" is remembered as the target reference before the local variable s is changed to refer to the string "two". As a result, the startsWith method is invoked for target object "one" with argument "two", so the result of the invocation is false, as the string "one" does not start with "two". It follows that the test program does not print "oops".

- - -

15.12.4.8 Example: Overriding

- -In the example:

-

class Point {
-        final int EDGE = 20;
-        int x, y;
-        void move(int dx, int dy) {
-                x += dx; y += dy;
-                if (Math.abs(x) >= EDGE || Math.abs(y) >= EDGE)
-                        clear();
-        }
-        void clear() {
-                System.out.println("\tPoint clear");
-                x = 0; y = 0;
-        }
-}
-class ColoredPoint extends Point {
-        int color;
-        void clear() {
-                System.out.println("\tColoredPoint clear");
-                super.clear();
-                color = 0;
-        }
-}
-
-the subclass ColoredPoint extends the clear abstraction defined by its superclass Point. It does so by overriding the clear method with its own method, which invokes the clear method of its superclass, using the form super.clear.

- -

This method is then invoked whenever the target object for an invocation of clear is a ColoredPoint. Even the method move in Point invokes the clear method of class ColoredPoint when the class of this is ColoredPoint, as shown by the output of this test program:

-
class Test {
-        public static void main(String[] args) {
-                Point p = new Point();
-                System.out.println("p.move(20,20):");
-                p.move(20, 20);
-                ColoredPoint cp = new ColoredPoint();
-                System.out.println("cp.move(20,20):");
-                cp.move(20, 20);
-                p = new ColoredPoint();
-                System.out.println("p.move(20,20), p colored:");
-                p.move(20, 20);
-        }
-}
-
-which is:

-

p.move(20,20):
-        Point clear
-cp.move(20,20):
-        ColoredPoint clear
-        Point clear
-p.move(20,20), p colored:
-        ColoredPoint clear
-        Point clear
-        
- -

Overriding is sometimes called "late-bound self-reference"; in this example it means that the reference to clear in the body of Point.move (which is really syntactic shorthand for this.clear) invokes a method chosen "late" (at run time, based on the run-time class of the object referenced by this) rather than a method chosen "early" (at compile time, based only on the type of this). This provides the programmer a powerful way of extending abstractions and is a key idea in object-oriented programming.

- - -

15.12.4.9 Example: Method Invocation using super

- -An overridden instance method of a superclass may be accessed by using the keyword super to access the members of the immediate superclass, bypassing any overriding declaration in the class that contains the method invocation.

- -

When accessing an instance variable, super means the same as a cast of this (§15.11.2), but this equivalence does not hold true for method invocation. This is demonstrated by the example:

-
class T1 {
-        String s() { return "1"; }
-}
-class T2 extends T1 {
-        String s() { return "2"; }
-}
-class T3 extends T2 {
-        String s() { return "3"; }
-        void test() {
-                System.out.println("s()=\t\t"+s());
-                System.out.println("super.s()=\t"+super.s());
-                System.out.print("((T2)this).s()=\t");
-                System.out.println(((T2)this).s());
-                System.out.print("((T1)this).s()=\t");
-                System.out.println(((T1)this).s());
-        }
-}
-class Test {
-        public static void main(String[] args) {
-                T3 t3 = new T3();
-                t3.test();
-        }
-}
-
-which produces the output:

-

s()=                   3
-super.s()=              2
-((T2)this).s()=         3
-((T1)this).s()=         3
-
- -

The casts to types T1 and T2 do not change the method that is invoked, because the instance method to be invoked is chosen according to the run-time class of the object referred to be this. A cast does not change the class of an object; it only checks that the class is compatible with the specified type.

- - -

15.13 Array Access Expressions

- -An array access expression refers to a variable that is a component of an array.

-


-ArrayAccess:
-        ExpressionName [ Expression ]
-        PrimaryNoNewArray [ Expression ]
-
-An array access expression contains two subexpressions, the array reference expression (before the left bracket) and the index expression (within the brackets). Note that the array reference expression may be a name or any primary expression that is not an array creation expression (§15.10).

- -The type of the array reference expression must be an array type (call it T[], an array whose components are of type T) or a compile-time error results. Then the type of the array access expression is the result of applying capture conversion (§5.1.10) to T.

- -The index expression undergoes unary numeric promotion (§); the promoted type must be int.

- -The result of an array reference is a variable of type T, namely the variable within the array selected by the value of the index expression. This resulting variable, which is a component of the array, is never considered final, even if the array reference was obtained from a final variable.

- - -

15.13.1 Runtime Evaluation of Array Access

- -An array access expression is evaluated using the following procedure:

-

- -

15.13.2 Examples: Array Access Evaluation Order

- -In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated. For example, in the (admittedly monstrous) expression a[(a=b)[3]], the expression a is fully evaluated before the expression (a=b)[3]; this means that the original value of a is fetched and remembered while the expression (a=b)[3] is evaluated. This array referenced by the original value of a is then subscripted by a value that is element 3 of another array (possibly the same array) that was referenced by b and is now also referenced by a.

- -

Thus, the example:

-
class Test {
-        public static void main(String[] args) {
-                int[] a = { 11, 12, 13, 14 };
-                int[] b = { 0, 1, 2, 3 };
-                System.out.println(a[(a=b)[3]]);
-        }
-}
-
-prints:

-

14
-
-because the monstrous expression's value is equivalent to a[b[3]] or a[3] or 14.

- -

If evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated. Thus, the example:

-
class Test {
-        public static void main(String[] args) {
-                int index = 1;
-                try {
-                        skedaddle()[index=2]++;
-                } catch (Exception e) {
-                        System.out.println(e + ", index=" + index);
-                }
-        }
-        static int[] skedaddle() throws Exception {
-                throw new Exception("Ciao");
-        }
-}
-
-prints:

-

java.lang.Exception: Ciao, index=1
-
-because the embedded assignment of 2 to index never occurs.

- -

If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at run time, but only after all parts of the array access expression have been evaluated and only if these evaluations completed normally. Thus, the example:

-
class Test {
-        public static void main(String[] args) {
-                int index = 1;
-                try {
-                        nada()[index=2]++;
-                } catch (Exception e) {
-                        System.out.println(e + ", index=" + index);
-                }
-        }
-        static int[] nada() { return null; }
-}
-
-prints:

-

java.lang.NullPointerException, index=2
-
-because the embedded assignment of 2 to index occurs before the check for a null pointer. As a related example, the program:

-

class Test {
-        public static void main(String[] args) {
-                int[] a = null;
-                try {
-                        int i = a[vamoose()];
-                        System.out.println(i);
-                } catch (Exception e) {
-                        System.out.println(e);
-                }
-        }
-        static int vamoose() throws Exception {
-                throw new Exception("Twenty-three skidoo!");
-        }
-}
-
-always prints:

-

java.lang.Exception: Twenty-three skidoo!
-
- -

A NullPointerException never occurs, because the index expression must be completely evaluated before any part of the indexing operation occurs, and that includes the check as to whether the value of the left-hand operand is null.

- - -

15.14 Postfix Expressions

- -Postfix expressions include uses of the postfix ++ and -- operators. Also, as discussed in §15.8, names are not considered to be primary expressions, but are handled separately in the grammar to avoid certain ambiguities. They become interchangeable only here, at the level of precedence of postfix expressions.

-


-PostfixExpression:
-        Primary
-        ExpressionName
-        PostIncrementExpression
-        PostDecrementExpression
-
- -

15.14.1 Expression Names

- -The rules for evaluating expression names are given in §6.5.6.

- - -

15.14.2 Postfix Increment Operator ++

-

-PostIncrementExpression:
-        PostfixExpression ++
-
-A postfix expression followed by a ++ operator is a postfix increment expression. The result of the postfix expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

- -Note that the binary numeric promotion mentioned above may include unboxing conversion (§5.1.8) and value set conversion (§5.1.13). If necessary, value set conversion is applied to the sum prior to its being stored in the variable.

- -A variable that is declared final cannot be incremented (unless it is a definitely unassigned (§16) blank final variable (§4.12.4)), because when an access of such a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix increment operator.

- - -

15.14.3 Postfix Decrement Operator --

-

-PostDecrementExpression:
-        PostfixExpression --
-
-A postfix expression followed by a -- operator is a postfix decrement expression. The result of the postfix expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. The type of the postfix decrement expression is the type of the variable. The result of the postfix decrement expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the postfix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable before the new value is stored.

- -Note that the binary numeric promotion mentioned above may include unboxing conversion (§5.1.8) and value set conversion (§5.1.13). If necessary, value set conversion is applied to the difference prior to its being stored in the variable.

- -A variable that is declared final cannot be decremented (unless it is a definitely unassigned (§16) blank final variable (§4.12.4)), because when an access of such a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix decrement operator.

- - -

15.15 Unary Operators

- -The unary operators include +, -, ++, --, ~, !, and cast operators. Expressions with unary operators group right-to-left, so that -~x means the same as -(~x).

-


-UnaryExpression:
-        PreIncrementExpression
-        PreDecrementExpression
-        + UnaryExpression
-        - UnaryExpression
-        UnaryExpressionNotPlusMinus
-
-PreIncrementExpression:
-        ++ UnaryExpression
-
-PreDecrementExpression:
-        -- UnaryExpression
-
-UnaryExpressionNotPlusMinus:
-        PostfixExpression
-        ~ UnaryExpression
-        ! UnaryExpression
-        CastExpression
-
-The following productions from §15.16 are repeated here for convenience:

-


-CastExpression:
-        ( PrimitiveType ) UnaryExpression
-        ( ReferenceType ) UnaryExpressionNotPlusMinus
-
- -

15.15.1 Prefix Increment Operator ++

- -A unary expression preceded by a ++ operator is a prefix increment expression. The result of the unary expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. The type of the prefix increment expression is the type of the variable. The result of the prefix increment expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.

- -Note that the binary numeric promotion mentioned above may include unboxing conversion (§5.1.8) and value set conversion (§5.1.13). If necessary, value set conversion is applied to the sum prior to its being stored in the variable.

- -A variable that is declared final cannot be incremented (unless it is a definitely unassigned (§16) blank final variable (§4.12.4)), because when an access of such a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix increment operator.

- - -

15.15.2 Prefix Decrement Operator --

- -A unary expression preceded by a -- operator is a prefix decrement expression. The result of the unary expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. The type of the prefix decrement expression is the type of the variable. The result of the prefix decrement expression is not a variable, but a value.

- -At run time, if evaluation of the operand expression completes abruptly, then the prefix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.

- -Note that the binary numeric promotion mentioned above may include unboxing conversion (§5.1.8) and value set conversion (§5.1.13). If necessary, format conversion is applied to the difference prior to its being stored in the variable.

- -A variable that is declared final cannot be decremented (unless it is a definitely unassigned (§16) blank final variable (§4.12.4)), because when an access of such a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix decrement operator.

- - -

15.15.3 Unary Plus Operator +

- -The type of the operand expression of the unary + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (§) is performed on the operand. The type of the unary plus expression is the promoted type of the operand. The result of the unary plus expression is not a variable, but a value, even if the result of the operand expression is a variable.

- -At run time, the value of the unary plus expression is the promoted value of the operand.

- - -

15.15.4 Unary Minus Operator -

- -The type of the operand expression of the unary - operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (§) is performed on the operand. The type of the unary minus expression is the promoted type of the operand.

- -Note that unary numeric promotion performs value set conversion (§5.1.13). Whatever value set the promoted operand value is drawn from, the unary negation operation is carried out and the result is drawn from that same value set. That result is then subject to further value set conversion.

- -At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.

- -For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.

- -For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0. Unary minus merely inverts the sign of a floating-point number. Special cases of interest:

-

- -

15.15.5 Bitwise Complement Operator ~

- -The type of the operand expression of the unary ~ operator must be a type that is convertible (§5.1.8) to a primitive integral type, or a compile-time error occurs. Unary numeric promotion (§) is performed on the operand. The type of the unary bitwise complement expression is the promoted type of the operand.

- -At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand; note that, in all cases, ~x equals (-x)-1.

- - -

15.15.6 Logical Complement Operator !

- -The type of the operand expression of the unary ! operator must be boolean or Boolean, or a compile-time error occurs. The type of the unary logical complement expression is boolean.

- -At run time, the operand is subject to unboxing conversion (§5.1.8) if necessary; the value of the unary logical complement expression is true if the (possibly converted) operand value is false and false if the (possibly converted) operand value is true.

- - -

15.16 Cast Expressions

- -A cast expression converts, at run time, a value of one numeric type to a similar value of another numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.

-


-CastExpression:
-        ( PrimitiveType Dimsopt ) UnaryExpression
-        ( ReferenceType ) UnaryExpressionNotPlusMinus
-        
-

-See §15.15 for a discussion of the distinction between UnaryExpression and UnaryExpressionNotPlusMinus.

- -The type of a cast expression is the result of applying capture conversion (§5.1.10) to the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the cast operator.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.

- -A cast operator has no effect on the choice of value set (§4.2.3) for a value of type float or type double. Consequently, a cast to type float within an expression that is not FP-strict (§15.4) does not necessarily cause its value to be converted to an element of the float value set, and a cast to type double within an expression that is not FP-strict does not necessarily cause its value to be converted to an element of the double value set.

- -It is a compile-time error if the compile-time type of the operand may never be cast to the type specified by the cast operator according to the rules of casting conversion (§5.5). Otherwise, at run-time, the operand value is converted (if necessary) by casting conversion to the type specified by the cast operator.

- -

Some casts result in an error at compile time. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time. See for §5.5 details.

- -A ClassCastException is thrown if a cast is found at run time to be impermissible.

- -

- - -

15.17 Multiplicative Operators

- -The operators *, /, and % are called the multiplicative operators. They have the same precedence and are syntactically left-associative (they group left-to-right).

-


-MultiplicativeExpression:
-        UnaryExpression
-        MultiplicativeExpression * UnaryExpression
-        MultiplicativeExpression / UnaryExpression
-        MultiplicativeExpression % UnaryExpression
-
-The type of each of the operands of a multiplicative operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). The type of a multiplicative expression is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

- -Note that binary numeric promotion performs unboxing conversion (§5.1.8) and value set conversion (§5.1.13).

- - -

15.17.1 Multiplication Operator *

- -The binary * operator performs multiplication, producing the product of its operands. Multiplication is a commutative operation if the operand expressions have no side effects. While integer multiplication is associative when the operands are all of the same type, floating-point multiplication is not associative.

- -If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

- -The result of a floating-point multiplication is governed by the rules of IEEE 754 arithmetic:

-

-Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a multiplication operator * never throws a run-time exception.

- - -

15.17.2 Division Operator /

- -The binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.

- -Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d·q||n|; moreover, q is positive when |n||d| and n and d have the same sign, but q is negative when |n||d| and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

- -The result of a floating-point division is determined by the specification of IEEE arithmetic:

-

-Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator / never throws a run-time exception

- - -

15.17.3 Remainder Operator %

- -The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.

- -

In C and C++, the remainder operator accepts only integral operands, but in the Java programming language, it also accepts floating-point operands.

- -The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown.Examples:

-

5%3 produces 2                 (note that 5/3 produces 1)
-5%(-3) produces 2               (note that 5/(-3) produces -1)
-(-5)%3 produces -2              (note that (-5)/3 produces -1)
-(-5)%(-3) produces -2           (note that (-5)/(-3) produces 1)
-
-The result of a floating-point remainder operation as computed by the % operator is not the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is not analogous to that of the usual integer remainder operator. Instead, the Java programming language defines % on floating-point operations to behave in a manner analogous to that of the integer remainder operator; this may be compared with the C library function fmod. The IEEE 754 remainder operation may be computed by the library routine Math.IEEEremainder.

- -The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

-

-Evaluation of a floating-point remainder operator % never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur.

- -

Examples:

-
5.0%3.0 produces 2.0
-5.0%(-3.0) produces 2.0
-(-5.0)%3.0 produces -2.0
-(-5.0)%(-3.0) produces -2.0
-
- -

15.18 Additive Operators

- -The operators + and - are called the additive operators. They have the same precedence and are syntactically left-associative (they group left-to-right).

-


-AdditiveExpression:
-        MultiplicativeExpression
-        AdditiveExpression + MultiplicativeExpression
-        AdditiveExpression - MultiplicativeExpression
-
-If the type of either operand of a + operator is String, then the operation is string concatenation.

- -Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

- -In every case, the type of each of the operands of the binary - operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

- - -

15.18.1 String Concatenation Operator +

- -If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28))that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string. If an operand of type String is null, then the string "null" is used instead of that operand.

- - -

15.18.1.1 String Conversion

- -Any type may be converted to type String by string conversion.

- -A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:

-

-This reference value is then converted to type String by string conversion.

- -Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

- -The toString method is defined by the primordial class Object; many classes override it, notably Boolean, Character, Integer, Long, Float, Double, and String.

- - -

15.18.1.2 Optimization of String Concatenation

- -An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

- -For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

- - -

15.18.1.3 Examples of String Concatenation

- -The example expression:

-

"The square root of 2 is " + Math.sqrt(2)
-
-produces the result:

-

"The square root of 2 is 1.4142135623730952"
-
- -

The + operator is syntactically left-associative, no matter whether it is later determined by type analysis to represent string concatenation or addition. In some cases care is required to get the desired result. For example, the expression:

-
-a + b + c
-
-is always regarded as meaning:

-

(a + b) + c
-
-Therefore the result of the expression:

-

1 + 2 + " fiddlers"
-
-is:

-

"3 fiddlers"
-
-but the result of:

-

"fiddlers " + 1 + 2
-
-is:

-

"fiddlers 12"
-
- -

In this jocular little example:

-
-class Bottles {
-        static void printSong(Object stuff, int n) {
-                String plural = (n == 1) ? "" : "s";
-                loop: while (true) {
-                        System.out.println(n + " bottle" + plural
-                                + " of " + stuff + " on the wall,");
-                        System.out.println(n + " bottle" + plural
-                                + " of " + stuff + ";");
-                        System.out.println("You take one down "
-                                + "and pass it around:");
-                        --n;
-                        plural = (n == 1) ? "" : "s";
-                        if (n == 0)
-                                break loop;
-                        System.out.println(n + " bottle" + plural
-                                + " of " + stuff + " on the wall!");
-                        System.out.println();
-                }
-                System.out.println("No bottles of " +
-                                stuff + " on the wall!");
-        }
-}
-
-

- -the method printSong will print a version of a children's song. Popular values for stuff include "pop" and "beer"; the most popular value for n is 100. Here is the output that results from Bottles.printSong("slime", 3):

- -

-

3 bottles of slime on the wall,
-3 bottles of slime;
-You take one down and pass it around:
-2 bottles of slime on the wall!
-
-2 bottles of slime on the wall,
-2 bottles of slime;
-You take one down and pass it around:
-1 bottle of slime on the wall!
-
-1 bottle of slime on the wall,
-1 bottle of slime;
-You take one down and pass it around:
-No bottles of slime on the wall!
-
-

- -

In the code, note the careful conditional generation of the singular "bottle" when appropriate rather than the plural "bottles"; note also how the string concatenation operator was used to break the long constant string:

- -

-
"You take one down and pass it around:"
-
- -

into two pieces to avoid an inconveniently long line in the source code.

- -

- - -

15.18.2 Additive Operators (+ and -) for Numeric Types

- -The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands. The binary - operator performs subtraction, producing the difference of two numeric operands.

- -Binary numeric promotion is performed on the operands (§5.6.2). The type of an additive expression on numeric operands is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

- -Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8).

- -Addition is a commutative operation if the operand expressions have no side effects. Integer addition is associative when the operands are all of the same type, but floating-point addition is not associative.

- -If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

- -The result of a floating-point addition is determined using the following rules of IEEE arithmetic:

-

-The binary - operator performs subtraction when applied to two operands of numeric type producing the difference of its operands; the left-hand operand is the minuend and the right-hand operand is the subtrahend. For both integer and floating-point subtraction, it is always the case that a-b produces the same result as a+(-b).

- -Note that, for integer values, subtraction from zero is the same as negation. However, for floating-point operands, subtraction from zero is not the same as negation, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0.

- -Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a run-time exception.

- -

- - -

15.19 Shift Operators

- -The shift operators include left shift <<, signed right shift >>, and unsigned right shift >>>; they are syntactically left-associative (they group left-to-right). The left-hand operand of a shift operator is the value to be shifted; the right-hand operand specifies the shift distance.

-


-ShiftExpression:
-        AdditiveExpression
-        ShiftExpression << AdditiveExpression
-        ShiftExpression >> AdditiveExpression
-        ShiftExpression >>> AdditiveExpression
-
-The type of each of the operands of a shift operator must be a type that is convertible (§5.1.8) to a primitive integral type, or a compile-time error occurs. Binary numeric promotion (§5.6.2) is not performed on the operands; rather, unary numeric promotion (§) is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.

- -If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

- -If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

- -At run time, shift operations are performed on the two's complement integer representation of the value of the left operand.

- -The value of n<<s is n left-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s.

- -The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is ⌊n/2s⌋. For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.

- -The value of n>>>s is n right-shifted s bit positions with zero-extension. If n is positive, then the result is the same as that of n>>s; if n is negative, the result is equal to that of the expression (n>>s)+(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)+(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a long value.)

- - -

15.20 Relational Operators

- -The relational operators are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.

-


-RelationalExpression:
-        ShiftExpression
-        RelationalExpression < ShiftExpression
-        RelationalExpression > ShiftExpression
-        RelationalExpression <= ShiftExpression
-        RelationalExpression >= ShiftExpression
-        RelationalExpression instanceof ReferenceType
-
-The type of a relational expression is always boolean.

- - -

15.20.1 Numerical Comparison Operators <, <=, >, and >=

- -The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

- -Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.

- -The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:

-

-Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

-

- -

15.20.2 Type Comparison Operator instanceof

- -The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs. It is a compile-time error if the ReferenceType mentioned after the instanceof operator does not denote a reifiable type (§4.7).

- -At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

- -If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

- -

Consider the example program:

-
class Point { int x, y; }
-class Element { int atomicNumber; }
-class Test {
-        public static void main(String[] args) {
-                Point p = new Point();
-                Element e = new Element();
-                if (e instanceof Point) {       // compile-time error
-                        System.out.println("I get your point!");
-                        p = (Point)e;           // compile-time error
-                }
-        }
-}
-
-This example results in two compile-time errors. The cast (Point)e is incorrect because no instance of Element or any of its possible subclasses (none are shown here) could possibly be an instance of any subclass of Point. The instanceof expression is incorrect for exactly the same reason. If, on the other hand, the class Point were a subclass of Element (an admittedly strange notion in this example):

-

class Point extends Element { int x, y; }
-
-then the cast would be possible, though it would require a run-time check, and the instanceof expression would then be sensible and valid. The cast (Point)e would never raise an exception because it would not be executed if the value of e could not correctly be cast to type Point.

- -

- - -

15.21 Equality Operators

- -The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, a==b==c parses as (a==b)==c. The result type of a==b is always boolean, and c must therefore be of type boolean or a compile-time error occurs. Thus, a==b==c does not test to see whether a, b, and c are all equal.

-


-EqualityExpression:
-        RelationalExpression
-        EqualityExpression == RelationalExpression
-        EqualityExpression != RelationalExpression
-
-The == (equal to) and the!= (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.

- -The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.

- -In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.

- - -

15.21.1 Numerical Equality Operators == and !=

- -If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

- -Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.

- -Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

-

-Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

-

- -

15.21.2 Boolean Equality Operators == and !=

- -If the operands of an equality operator are both of type boolean, or if one operand is of type boolean and the other is of type Boolean, then the operation is boolean equality. The boolean equality operators are associative.

- -If one of the operands is of type Boolean it is subjected to unboxing conversion (§5.1.8).

- -The result of == is true if the operands (after any required unboxing conversion) are both true or both false; otherwise, the result is false.

- -The result of != is false if the operands are both true or both false; otherwise, the result is true. Thus != behaves the same as ^ (§15.22.2) when applied to boolean operands.

- - -

15.21.3 Reference Equality Operators == and !=

- -If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

- -A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal.

- -At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

- -The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.

- -

While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of two strings s and t can be tested for equality by the method invocation s.equals(t). See also §3.10.5.

- - -

15.22 Bitwise and Logical Operators

- -The bitwise operators and logical operators include the AND operator &, exclusive OR operator ^, and inclusive OR operator |. These operators have different precedence, with & having the highest precedence and | the lowest precedence. Each of these operators is syntactically left-associative (each groups left-to-right). Each operator is commutative if the operand expressions have no side effects. Each operator is associative.

-


-AndExpression:
-        EqualityExpression
-        AndExpression & EqualityExpression
-
-ExclusiveOrExpression:
-        AndExpression
-        ExclusiveOrExpression ^ AndExpression
-
-InclusiveOrExpression:
-        ExclusiveOrExpression
-        InclusiveOrExpression | ExclusiveOrExpression
-
-The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type boolean. All other cases result in a compile-time error.

- - -

15.22.1 Integer Bitwise Operators &, ^, and |

- -When both operands of an operator &, ^, or | are of a type that is convertible (§5.1.8) to a primitive integral type, binary numeric promotion is first performed on the operands (§5.6.2). The type of the bitwise operator expression is the promoted type of the operands.

- -For &, the result value is the bitwise AND of the operand values.

- -For ^, the result value is the bitwise exclusive OR of the operand values.

- -For |, the result value is the bitwise inclusive OR of the operand values.

- -

For example, the result of the expression 0xff00 & 0xf0f0 is 0xf000. The result of 0xff00 ^ 0xf0f0 is 0x0ff0.The result of 0xff00 | 0xf0f0 is 0xfff0.

- - -

15.22.2 Boolean Logical Operators &, ^, and |

- -When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

- -

- -For &, the result value is true if both operand values are true; otherwise, the result is false.

- -For ^, the result value is true if the operand values are different; otherwise, the result is false.

- -For |, the result value is false if both operand values are false; otherwise, the result is true.

- - -

15.23 Conditional-And Operator &&

- -The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)&&(b))&&(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)&&((b)&&(c)).

-


-ConditionalAndExpression:
-        InclusiveOrExpression
-        ConditionalAndExpression && InclusiveOrExpression
-
-Each operand of && must be of type boolean or Boolean, or a compile-time error occurs. The type of a conditional-and expression is always boolean.

- -At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8); if the resulting value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8); the resulting value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

- - -

15.24 Conditional-Or Operator ||

- -The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)||(b))||(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)||((b)||(c)).

-


-ConditionalOrExpression:
-        ConditionalAndExpression
-        ConditionalOrExpression || ConditionalAndExpression
-
-Each operand of || must be of type boolean or Boolean, or a compile-time error occurs. The type of a conditional-or expression is always boolean.

- -At run time, the left-hand operand expression is evaluated first; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8); if the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated; if the result has type Boolean, it is subjected to unboxing conversion (§5.1.8); the resulting value becomes the value of the conditional-or expression.

- -

Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

- - -

15.25 Conditional Operator ? :

- -The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

- -The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

-


-ConditionalExpression:
-        ConditionalOrExpression
-        ConditionalOrExpression ? Expression : ConditionalExpression
-
-The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.

- -The first expression must be of type boolean or Boolean, or a compile-time error occurs.

- -Note that it is a compile-time error for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear (§14.8).

- -The type of a conditional expression is determined as follows:

-

-At run time, the first operand expression of the conditional expression is evaluated first; if necessary, unboxing conversion is performed on the result; the resulting boolean value is then used to choose either the second or the third operand expression:

-

-The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated above. This conversion may include boxing (§5.1.7) or unboxing conversion. The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.

- - -

15.26 Assignment Operators

- -There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

-


-AssignmentExpression:
-        ConditionalExpression
-        Assignment
-
-Assignment:
-        LeftHandSide AssignmentOperator AssignmentExpression
-
-LeftHandSide:
-        ExpressionName
-        FieldAccess
-        ArrayAccess
-
-AssignmentOperator: one of
-        = *= /= %= += -= <<= >>= >>>= &= ^= |=
-
-The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. This operand may be a named variable, such as a local variable or a field of the current object or class, or it may be a computed variable, as can result from a field access (§15.11) or an array access (§15.13). The type of the assignment expression is the type of the variable after capture conversion (§5.1.10).

- -At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

- -A variable that is declared final cannot be assigned to (unless it is a definitely unassigned (§16) blank final variable (§4.12.4)), because when an access of such a final variable is used as an expression, the result is a value, not a variable, and so it cannot be used as the first operand of an assignment operator.

- - -

15.26.1 Simple Assignment Operator =

- -A compile-time error occurs if the type of the right-hand operand cannot be converted to the type of the variable by assignment conversion (§5.2).

- -At run time, the expression is evaluated in one of three ways:

-

-

Otherwise, the value of the right-hand operand is converted to the type of the left-hand variable, is subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.The rules for assignment to an array component are illustrated by the following example program:

-
-class ArrayReferenceThrow extends RuntimeException { }
-class IndexThrow extends RuntimeException { }
-class RightHandSideThrow extends RuntimeException { }
-class IllustrateSimpleArrayAssignment {
-        static Object[] objects = { new Object(), new Object() };
-        static Thread[] threads = { new Thread(), new Thread() };
-        static Object[] arrayThrow() {
-                throw new ArrayReferenceThrow();
-        }
-        static int indexThrow() { throw new IndexThrow(); }
-        static Thread rightThrow() {
-                throw new RightHandSideThrow();
-        }
-        static String name(Object q) {
-                String sq = q.getClass().getName();
-                int k = sq.lastIndexOf('.');
-                return (k < 0) ? sq : sq.substring(k+1);
-        }
-        static void testFour(Object[] x, int j, Object y) {
-                String sx = x == null ? "null" : name(x[0]) + "s";
-                String sy = name(y);
-                System.out.println();
-                try {
-                        System.out.print(sx + "[throw]=throw => ");
-                        x[indexThrow()] = rightThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sx + "[throw]=" + sy + " => ");
-                        x[indexThrow()] = y;
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sx + "[" + j + "]=throw => ");
-                        x[j] = rightThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sx + "[" + j + "]=" + sy + " => ");
-                        x[j] = y;
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-        }
-        public static void main(String[] args) {
-                try {
-                        System.out.print("throw[throw]=throw => ");
-                        arrayThrow()[indexThrow()] = rightThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[throw]=Thread => ");
-                        arrayThrow()[indexThrow()] = new Thread();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[1]=throw => ");
-                        arrayThrow()[1] = rightThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[1]=Thread => ");
-                        arrayThrow()[1] = new Thread();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                testFour(null, 1, new StringBuffer());
-                testFour(null, 1, new StringBuffer());
-                testFour(null, 9, new Thread());
-                testFour(null, 9, new Thread());
-                testFour(objects, 1, new StringBuffer());
-                testFour(objects, 1, new Thread());
-                testFour(objects, 9, new StringBuffer());
-                testFour(objects, 9, new Thread());
-                testFour(threads, 1, new StringBuffer());
-                testFour(threads, 1, new Thread());
-                testFour(threads, 9, new StringBuffer());
-                testFour(threads, 9, new Thread());
-        }
-}
-
-This program prints:

-

throw[throw]=throw => ArrayReferenceThrow
-throw[throw]=Thread => ArrayReferenceThrow
-throw[1]=throw => ArrayReferenceThrow
-throw[1]=Thread => ArrayReferenceThrow
-null[throw]=throw => IndexThrow
-null[throw]=StringBuffer => IndexThrow
-null[1]=throw => RightHandSideThrow
-null[1]=StringBuffer => NullPointerException
-null[throw]=throw => IndexThrow
-null[throw]=StringBuffer => IndexThrow
-null[1]=throw => RightHandSideThrow
-null[1]=StringBuffer => NullPointerException
-null[throw]=throw => IndexThrow
-null[throw]=Thread => IndexThrow
-null[9]=throw => RightHandSideThrow
-null[9]=Thread => NullPointerException
-null[throw]=throw => IndexThrow
-null[throw]=Thread => IndexThrow
-null[9]=throw => RightHandSideThrow
-null[9]=Thread => NullPointerException
-Objects[throw]=throw => IndexThrow
-Objects[throw]=StringBuffer => IndexThrow
-Objects[1]=throw => RightHandSideThrow
-Objects[1]=StringBuffer => Okay!
-Objects[throw]=throw => IndexThrow
-Objects[throw]=Thread => IndexThrow
-Objects[1]=throw => RightHandSideThrow
-Objects[1]=Thread => Okay!
-Objects[throw]=throw => IndexThrow
-Objects[throw]=StringBuffer => IndexThrow
-Objects[9]=throw => RightHandSideThrow
-Objects[9]=StringBuffer => ArrayIndexOutOfBoundsException
-Objects[throw]=throw => IndexThrow
-Objects[throw]=Thread => IndexThrow
-Objects[9]=throw => RightHandSideThrow
-Objects[9]=Thread => ArrayIndexOutOfBoundsException
-Threads[throw]=throw => IndexThrow
-Threads[throw]=StringBuffer => IndexThrow
-Threads[1]=throw => RightHandSideThrow
-Threads[1]=StringBuffer => ArrayStoreException
-Threads[throw]=throw => IndexThrow
-Threads[throw]=Thread => IndexThrow
-Threads[1]=throw => RightHandSideThrow
-Threads[1]=Thread => Okay!
-Threads[throw]=throw => IndexThrow
-Threads[throw]=StringBuffer => IndexThrow
-Threads[9]=throw => RightHandSideThrow
-Threads[9]=StringBuffer => ArrayIndexOutOfBoundsException
-Threads[throw]=throw => IndexThrow
-Threads[throw]=Thread => IndexThrow
-Threads[9]=throw => RightHandSideThrow
-Threads[9]=Thread => ArrayIndexOutOfBoundsException
-
-The most interesting case of the lot is the one thirteenth from the end:

-

Threads[1]=StringBuffer => ArrayStoreException
-
-which indicates that the attempt to store a reference to a StringBuffer into an array whose components are of type Thread throws an ArrayStoreException. The code is type-correct at compile time: the assignment has a left-hand side of type Object[] and a right-hand side of type Object. At run time, the first actual argument to method testFour is a reference to an instance of "array of Thread" and the third actual argument is a reference to an instance of class StringBuffer.

- - -

15.26.2 Compound Assignment Operators

- -A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

- -For example, the following code is correct:

-


-short x = 3;
-x += 4.6;
-
-and results in x having the value 7 because it is equivalent to:

-


-short x = 3;
-x = (short)(x + 4.6);
-
-At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:

-

-If the left-hand operand expression is an array access expression (§15.13), then many steps are required:

-

-Otherwise, the String result of the binary operation is stored into the array component.

- -

The rules for compound assignment to an array component are illustrated by the following example program:

-
class ArrayReferenceThrow extends RuntimeException { }
-class IndexThrow extends RuntimeException { }
-class RightHandSideThrow extends RuntimeException { }
-class IllustrateCompoundArrayAssignment {
-        static String[] strings = { "Simon", "Garfunkel" };
-        static double[] doubles = { Math.E, Math.PI };
-        static String[] stringsThrow() {
-                throw new ArrayReferenceThrow();
-        }
-        static double[] doublesThrow() {
-                throw new ArrayReferenceThrow();
-        }
-        static int indexThrow() { throw new IndexThrow(); }
-        static String stringThrow() {
-                throw new RightHandSideThrow();
-        }
-        static double doubleThrow() {
-                throw new RightHandSideThrow();
-        }
-        static String name(Object q) {
-                String sq = q.getClass().getName();
-                int k = sq.lastIndexOf('.');
-                return (k < 0) ? sq : sq.substring(k+1);
-        }
-        static void testEight(String[] x, double[] z, int j) {
-                String sx = (x == null) ? "null" : "Strings";
-                String sz = (z == null) ? "null" : "doubles";
-                System.out.println();
-                try {
-                        System.out.print(sx + "[throw]+=throw => ");
-                        x[indexThrow()] += stringThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sz + "[throw]+=throw => ");
-                        z[indexThrow()] += doubleThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sx + "[throw]+=\"heh\" => ");
-                        x[indexThrow()] += "heh";
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sz + "[throw]+=12345 => ");
-                        z[indexThrow()] += 12345;
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sx + "[" + j + "]+=throw => ");
-                        x[j] += stringThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sz + "[" + j + "]+=throw => ");
-                        z[j] += doubleThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sx + "[" + j + "]+=\"heh\" => ");
-                        x[j] += "heh";
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print(sz + "[" + j + "]+=12345 => ");
-                        z[j] += 12345;
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-        }
-        public static void main(String[] args) {
-                try {
-                        System.out.print("throw[throw]+=throw => ");
-                        stringsThrow()[indexThrow()] += stringThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[throw]+=throw => ");
-                        doublesThrow()[indexThrow()] += doubleThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[throw]+=\"heh\" => ");
-                        stringsThrow()[indexThrow()] += "heh";
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[throw]+=12345 => ");
-                        doublesThrow()[indexThrow()] += 12345;
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[1]+=throw => ");
-                        stringsThrow()[1] += stringThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[1]+=throw => ");
-                        doublesThrow()[1] += doubleThrow();
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[1]+=\"heh\" => ");
-                        stringsThrow()[1] += "heh";
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                try {
-                        System.out.print("throw[1]+=12345 => ");
-                        doublesThrow()[1] += 12345;
-                        System.out.println("Okay!");
-                } catch (Throwable e) { System.out.println(name(e)); }
-                testEight(null, null, 1);
-                testEight(null, null, 9);
-                testEight(strings, doubles, 1);
-                testEight(strings, doubles, 9);
-        }
-}
-
-This program prints:

-

throw[throw]+=throw => ArrayReferenceThrow
-throw[throw]+=throw => ArrayReferenceThrow
-throw[throw]+="heh" => ArrayReferenceThrow
-throw[throw]+=12345 => ArrayReferenceThrow
-throw[1]+=throw => ArrayReferenceThrow
-throw[1]+=throw => ArrayReferenceThrow
-throw[1]+="heh" => ArrayReferenceThrow
-throw[1]+=12345 => ArrayReferenceThrow
-null[throw]+=throw => IndexThrow
-null[throw]+=throw => IndexThrow
-null[throw]+="heh" => IndexThrow
-null[throw]+=12345 => IndexThrow
-null[1]+=throw => NullPointerException
-null[1]+=throw => NullPointerException
-null[1]+="heh" => NullPointerException
-null[1]+=12345 => NullPointerException
-null[throw]+=throw => IndexThrow
-null[throw]+=throw => IndexThrow
-null[throw]+="heh" => IndexThrow
-null[throw]+=12345 => IndexThrow
-null[9]+=throw => NullPointerException
-null[9]+=throw => NullPointerException
-null[9]+="heh" => NullPointerException
-null[9]+=12345 => NullPointerException
-Strings[throw]+=throw => IndexThrow
-doubles[throw]+=throw => IndexThrow
-Strings[throw]+="heh" => IndexThrow
-doubles[throw]+=12345 => IndexThrow
-Strings[1]+=throw => RightHandSideThrow
-doubles[1]+=throw => RightHandSideThrow
-Strings[1]+="heh" => Okay!
-doubles[1]+=12345 => Okay!
-Strings[throw]+=throw => IndexThrow
-doubles[throw]+=throw => IndexThrow
-Strings[throw]+="heh" => IndexThrow
-doubles[throw]+=12345 => IndexThrow
-Strings[9]+=throw => ArrayIndexOutOfBoundsException
-doubles[9]+=throw => ArrayIndexOutOfBoundsException
-Strings[9]+="heh" => ArrayIndexOutOfBoundsException
-doubles[9]+=12345 => ArrayIndexOutOfBoundsException
-
-The most interesting cases of the lot are tenth and eleventh from the end:

-

Strings[1]+=throw => RightHandSideThrow
-doubles[1]+=throw => RightHandSideThrow
-
-They are the cases where a right-hand side that throws an exception actually gets to throw the exception; moreover, they are the only such cases in the lot. This demonstrates that the evaluation of the right-hand operand indeed occurs after the checks for a null array reference value and an out-of-bounds index value.

- -

The following program illustrates the fact that the value of the left-hand side of a compound assignment is saved before the right-hand side is evaluated:

-
class Test {
-        public static void main(String[] args) {
-                int k = 1;
-                int[] a = { 1 };
-                k += (k = 4) * (k + 2);
-                a[0] += (a[0] = 4) * (a[0] + 2);
-                System.out.println("k==" + k + " and a[0]==" + a[0]);
-        }
-}
-
-This program prints:

-

k==25 and a[0]==25
-
-The value 1 of k is saved by the compound assignment operator += before its right-hand operand (k = 4) * (k + 2) is evaluated. Evaluation of this right-hand operand then assigns 4 to k, calculates the value 6 for k + 2, and then multiplies 4 by 6 to get 24. This is added to the saved value 1 to get 25, which is then stored into k by the += operator. An identical analysis applies to the case that uses a[0]. In short, the statements

-

k += (k = 4) * (k + 2);
-a[0] += (a[0] = 4) * (a[0] + 2);
-
-behave in exactly the same manner as the statements:

-

k = k + (k = 4) * (k + 2);
-a[0] = a[0] + (a[0] = 4) * (a[0] + 2);
-
- -

15.27 Expression

- -An Expression is any assignment expression:

-


-Expression:
-        AssignmentExpression
-        
- -

Unlike C and C++, the Java programming language has no comma operator.

- - -

15.28 Constant Expression

-

-ConstantExpression:
-        Expression
-
-

-A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

-

-Compile-time constant expressions are used in case labels in switch statements (§14.11) and have a special significance for assignment conversion (§5.2). Compile-time constants of type String are always "interned" so as to share unique instances, using the method String.intern.

- -A compile-time constant expression is always treated as FP-strict (§15.4), even if it occurs in a context where a non-constant expression would not be considered to be FP-strict.

- -

Examples of constant expressions:

-
true
-(short)(1*2*3*4*5*6)
-Integer.MAX_VALUE / 2
-2.0 * Math.PI
-"The integer " + Long.MAX_VALUE + " is mighty big."
-
- -
-

- - - -
Contents | Prev | Next | IndexJava Language Specification
-Third Edition
-

- -Copyright © 1996-2005 Sun Microsystems, Inc. -All rights reserved -
-Please send any comments or corrections via our feedback form -
- - diff --git a/topics/java/jls3/impl.html b/topics/java/jls3/impl.html new file mode 100644 index 00000000..d57e5897 --- /dev/null +++ b/topics/java/jls3/impl.html @@ -0,0 +1,239 @@ + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + +

+ + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/syntax.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/syntax.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + diff --git a/topics/java/jls3/read.html b/topics/java/jls3/read.html new file mode 100644 index 00000000..0a7a2758 --- /dev/null +++ b/topics/java/jls3/read.html @@ -0,0 +1,1912 @@ + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/typesValues.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/typesValues.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/names.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/names.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/packages.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/packages.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/classes.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/classes.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/interfaces.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/interfaces.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/arrays.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/arrays.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/statements.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/statements.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + + + + + + + + + + + + +Sun Microsystems + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ + + + + + + + +
+ +
+ 
+ + + +
Page Not Found 
+ + + + + + + + +
+ + + + + + + + +
We are sorry, the page you have requested was not found on our system. Based +upon the url that you requested, we would like to recommend pages that match your requested url. +If you prefer, you may navigate through our site or use our search for your page.
+
+

If you are certain that this URL is valid, please send us +feedback +about the broken link. +

+
+
+ + + +
+Your URL:   http://java.sun.com/reads/books/jls/third_edition/html/expressions.html +

+Recommended URLs to try:
+
+
+ + 
+ + + +
+
+
+ + + + + +
Search for your page
+If you prefer, we have suggested words that you may wish use to search our site.

+ +
+URL Requested:   http://java.sun.com/reads/books/jls/third_edition/html/expressions.html
+ 
+ + +
+ 
+ +
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + +

+

+
 +
+
+ + + + + + diff --git a/topics/java/lci/snapshot/architecture_large.pdf b/topics/java/lci/snapshot/architecture_large.pdf index 7a1ebbccd14456d13755ae1f15d00c3f6e4bcd15..29e21f876f3fb5d56d04d18d9420556d31d0b048 100644 GIT binary patch delta 35755 zcmX6^Q+QZyvyE-rw#~+9tj0!TJ3F>*TaE3cv2ELK!=C)#x!afX%w99IX03TY3c&oU zz~WVajYNvEnB1EO+WQ78GdlBZHg={o3{9#GNh-V%d2BYlrbvl~c0ob@t;YFUBDXw= z9b}$&6kJ@)AGXfr!BRW}$PPRp(7U|^|2*E0RtW)~&*wio9S0NKe(oa+4+43LX%`;v z&ra`Gz<$3$?+bkIzlHq};SYW0$1VqyT=ai{%g9|ZVBp918K(Tt?Zk>FH|*Nw{nhK8 z(BLxe-^#WCVfQP^d(=5}rF+@S%eukzNaJT~u<**v$-;wGX57ldLpyOPd>+5+%z=xL z!iw1EhtuWB$(|F@QugEf`=;Kj;~_e%1nq7X^9WdO=ZWVf5~PH1PA+w&g67Y%9cFa^ zy|DT`^k5WGSZhR|?UJx&y9}1`(dm8TP7%RKJ`L)9h=VXa#L*0g6TbKDZZ+E^-uTg_Za zn}t=@z{;o_qwfsh&ypUSiuQAh{hC&Am;85eF(T~V%lrQKPf?8D2;2|R71u#$?g*bw z$K^mvLoD$C=7$H5Ya~tcSD%ib^NL01e9fgh(UV7>c*nK$GjAvK7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