<html>
<head>
<title> Expressions</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>

<table border="0" width="100%">
<tr>
<td><a href="jTOC.doc.html">Contents</a> | <a href="statements.doc.html">Prev</a> | <a href="defAssign.doc.html">Next</a> | <a href="jIX.fm.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">Second Edition</font></td></tr></table>
<hr><br>

<a name="4709"></a>
<p><strong>
CHAPTER
15 </strong></p>
<a name="44393"></a>
<h1>Expressions</h1>
<hr><p>
<a name="11757"></a>
Much of the work in a program is done by evaluating <em>expressions</em>, 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.<p>
<a name="236101"></a>
This chapter specifies the meanings of expressions and the rules for their evaluation.<p>
<a name="228862"></a>
<h2>15.1    Evaluation, Denotation, and Result</h2>
<a name="290570"></a>
When an expression in a program is <em>evaluated</em> (<em>executed</em>), the <em>result </em>denotes one of three things:<p>
<ul><a name="228896"></a>
<li>A variable <a href="typesValues.doc.html#18470">(&#167;4.5)</a> (in C, this would be called an <em>lvalue</em>)
<a name="19788"></a>
<li>A value (<a href="typesValues.doc.html#85587">&#167;4.2</a>, <a href="typesValues.doc.html#9317">&#167;4.3</a>)
<a name="229505"></a>
<li>Nothing (the expression is said to be <code>void</code>)
</ul><a name="233971"></a>
Evaluation of an expression can also produce side effects, because expressions may contain embedded assignments, increment operators, decrement operators, and method invocations.<p>
<a name="229523"></a>
An expression denotes nothing if and only if it is a method invocation <a href="expressions.doc.html#20448">(&#167;15.12)</a> that invokes a method that does not return a value, that is, a method declared <code>void</code> <a href="classes.doc.html#40420">(&#167;8.4)</a>. Such an expression can be used only as an expression statement <a href="statements.doc.html#5984">(&#167;14.8)</a>, 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.<p>
<a name="249221"></a>
Value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a> is applied to the result of every expression that produces a value.<p>
<a name="39859"></a>
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.<p>
<a name="229188"></a>
<h2>15.2    Variables as Values</h2>
<a name="229204"></a>
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 <em>value</em> of the expression.<p>
<a name="249233"></a>
If the value of a variable of type <code>float</code> or <code>double</code> is used in this manner, then value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a> is applied to the value of the variable.<p>
<a name="198550"></a>
<h2>15.3    Type of an Expression</h2>
<a name="229255"></a>
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.<p>
<a name="229277"></a>
The value of an expression is always assignment compatible <a href="conversions.doc.html#184206">(&#167;5.2)</a> with the type of the expression, just as the value stored in a variable is always compatible with the type of the variable. <p>
<a name="264235"></a>
In other words, the value of an expression whose type is <i>T</i> is always suitable for assignment to a variable of type <i>T</i>.<p>
<a name="264237"></a>
Note that an expression whose type is a class type <i>F</i> that is declared <code>final</code> is guaranteed to have a value that is either a null reference or an object whose class is <i>F</i> itself, because <code>final</code> types have no subclasses.<p>
<a name="249198"></a>
<h2>15.4    FP-strict Expressions</h2>
<a name="272660"></a>
If the type of an expression is <code>float</code> or <code>double</code>, then there is a question as to what value set <a href="typesValues.doc.html#9208">(&#167;4.2.3)</a> the value of the expression is drawn from. This is governed by the rules of value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>; these rules in turn depend on whether or not the expression is <em>FP-strict</em>.<p>
<a name="272652"></a>
Every compile-time constant expression <a href="expressions.doc.html#5313">(&#167;15.28)</a> 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 <em>any</em> such declaration bears the <code>strictfp</code> modifier, then the expression is FP-strict.<p>
<a name="286261"></a>
If a class, interface, or method, <i>X</i>, is declared <code>strictfp</code>, then <i>X</i> and any class, interface, method, constructor, instance initializer, static initializer or variable initializer within <i>X</i> is said to be <em>FP-strict</em>.<p>
<a name="272653"></a>
It follows that an expression is not FP-strict if and only if it is not a compile-time constant expression <em>and</em> it does not appear within any declaration that has the <code>strictfp</code> modifier.<p>
<a name="290065"></a>
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.<p>
<a name="290072"></a>
<h2>15.5    Expressions and Run-Time Checks</h2>
<a name="233993"></a>
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 <code>null</code>, 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:<p>
<ul><a name="79422"></a>
<li>Method invocation <a href="expressions.doc.html#20448">(&#167;15.12)</a>. The particular method used for an invocation <code>o.m(</code>...<code>)</code> is chosen based on the methods that are part of the class or interface that is the type of <code>o</code>. For instance methods, the class of the object referenced by the run-time value of <code>o</code> participates because a subclass may override a specific method already declared in a parent class so that this overriding method is invoked. (The overriding method may or may not choose to further invoke the original overridden <code>m</code> method.)
<a name="79436"></a>
<li>The <code>instanceof</code> operator <a href="expressions.doc.html#80289">(&#167;15.20.2)</a>. An expression whose type is a reference type may be tested using <code>instanceof</code> to find out whether the class of the object referenced by the run-time value of the expression is assignment compatible <a href="conversions.doc.html#184206">(&#167;5.2)</a> with some other reference type.
<a name="35797"></a>
<li>Casting (<a href="conversions.doc.html#20232">&#167;5.5</a>, <a href="expressions.doc.html#238146">&#167;15.16</a>). The class of the object referenced by the run-time value of the operand expression might not be compatible with the type specified by the cast. For reference types, this may require a run-time check that throws an exception if the class of the referenced object, as determined at run time, is not assignment &#32;compatible <a href="conversions.doc.html#184206">(&#167;5.2)</a> with the target type.
<a name="35800"></a>
<li>Assignment to an array component of reference type (<a href="arrays.doc.html#11430">&#167;10.10</a>, <a href="expressions.doc.html#239587">&#167;15.13</a>, <a href="expressions.doc.html#5295">&#167;15.26.1</a>). The type-checking rules allow the array type <i>S</i><code>[]</code> to be treated as a subtype of <i>T</i><code>[]</code> if <i>S</i> is a subtype of <i>T</i>, but this requires a run-time check for assignment to an array component, similar to the check performed for a cast.
<a name="79438"></a>
<li>Exception handling <a href="statements.doc.html#79311">(&#167;14.19)</a>. An exception is caught by a <code>catch</code> clause only if the class of the thrown exception object is an <code>instanceof</code> the type of the formal parameter of the <code>catch</code> clause.
</ul><a name="35847"></a>
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:<p>
<ul><a name="79443"></a>
<li>In a cast, when the actual class of the object referenced by the value of the operand expression is not compatible with the target type specified by the cast operator (<a href="conversions.doc.html#20232">&#167;5.5</a>, <a href="expressions.doc.html#238146">&#167;15.16</a>); in this case a <code>ClassCastException</code> is thrown.
<a name="79444"></a>
<li>In an assignment to an array component of reference type, when the actual class of the object referenced by the value to be assigned is not compatible with the actual run-time component type of the array (<a href="arrays.doc.html#11430">&#167;10.10</a>, <a href="expressions.doc.html#239587">&#167;15.13</a>, <a href="expressions.doc.html#5295">&#167;15.26.1</a>); in this case an <code>ArrayStoreException</code> is thrown.
<a name="79445"></a>
<li>When an exception is not caught by any <code>catch</code> handler <a href="exceptions.doc.html#44153">(&#167;11.3)</a>; in this case the thread of control that encountered the exception first invokes the method <code>uncaughtException</code> &#32; for its thread group and then terminates.
</ul><a name="79448"></a>
<h2>15.6    Normal and Abrupt Completion of Evaluation</h2>
<a name="79449"></a>
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 <em>complete normally</em>. <p>
<a name="217304"></a>
If, however, evaluation of an expression throws an exception, then the expression is said to <em>complete abruptly</em>. An abrupt completion always has an associated <em>reason</em>, which is always a <code>throw</code> with a given value.<p>
<a name="217294"></a>
Run-time exceptions are thrown by the predefined operators as follows:<p>
<ul><a name="43791"></a>
<li>A class instance creation expression <a href="expressions.doc.html#41147">(&#167;15.9)</a>, array creation expression <a href="expressions.doc.html#46168">(&#167;15.10)</a>, or string concatenation operatior expression <a href="expressions.doc.html#39990">(&#167;15.18.1)</a> throws an <code>OutOfMemoryError</code> if there is insufficient memory available.
<a name="43795"></a>
<li>An array creation expression throws a <code>NegativeArraySizeException</code> if the value of any dimension expression is less than zero <a href="expressions.doc.html#46168">(&#167;15.10)</a>.
<a name="43780"></a>
<li>A field access <a href="expressions.doc.html#41267">(&#167;15.11)</a> throws a <code>NullPointerException</code> if the value of the object reference &#32;expression is <code>null</code>.
<a name="43784"></a>
<li>A method invocation expression <a href="expressions.doc.html#20448">(&#167;15.12)</a> that invokes an instance method throws a <code>NullPointerException</code> if the target reference is <code>null</code>.
<a name="43730"></a>
<li>An array access <a href="expressions.doc.html#239587">(&#167;15.13)</a> throws a <code>NullPointerException</code> if the value of the array reference &#32;expression is <code>null</code>.
<a name="43758"></a>
<li>An array access <a href="expressions.doc.html#239587">(&#167;15.13)</a> throws an <code>ArrayIndexOutOfBoundsException</code> if the value &#32;of the array index expression is negative or greater than or equal to the <code>length</code> of the array.
<a name="217340"></a>
<li>A cast <a href="expressions.doc.html#238146">(&#167;15.16)</a> throws a <code>ClassCastException</code> if a cast is found to be impermissible at run time.
<a name="217346"></a>
<li>An integer division <a href="expressions.doc.html#5047">(&#167;15.17.2)</a> or integer remainder <a href="expressions.doc.html#24956">(&#167;15.17.3)</a> operator throws an <code>ArithmeticException</code> if the value of the right-hand operand expression is zero.
<a name="234027"></a>
<li>An assignment to an array component of reference type <a href="expressions.doc.html#5295">(&#167;15.26.1)</a> throws an <code>ArrayStoreException</code> when the value to be assigned is not compatible with the component type of the array.
</ul><a name="21217"></a>
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.<p>
<a name="6969"></a>
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 &#32;"complete abruptly" are also applied to the execution of statements <a href="statements.doc.html#5894">(&#167;14.1)</a>. A &#32;statement may complete abruptly for a variety of reasons, not just because an exception is thrown.<p>
<a name="79456"></a>
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.<p>
<a name="4779"></a>
<h2>15.7    Evaluation Order</h2>
<a name="264242"></a>
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific <em>evaluation order</em>, namely, from left to right.<p>
<a name="264247"></a>
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 &#32;operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.<p>
<a name="18498"></a>
<h3>15.7.1    Evaluate Left-Hand Operand First</h3>
<a name="264252"></a>
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.<p>
<a name="18540"></a>
Thus:<p>
<blockquote><pre>class Test {
       public static void main(String[] args) {
               int i = 2;
               int j = (i=3) * i;
               System.out.println(j);
       }
}
</pre></blockquote><a name="18539"></a>
prints:<p>
<blockquote><pre><code>9
</code></pre></blockquote><a name="35994"></a>
It is not permitted for it to print <code>6</code> instead of <code>9</code>.<p>
<a name="240786"></a>
If the operator is a compound-assignment operator <a href="expressions.doc.html#5304">(&#167;15.26.2)</a>, 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:<p>
<blockquote><pre>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);
       }
}
</pre></blockquote><a name="18725"></a>
prints:<p>
<blockquote><pre>12
12
</pre></blockquote><a name="264257"></a>
because the two assignment statements both fetch and remember the value of the left-hand operand, which is <code>9</code>, before the right-hand operand of the addition is evaluated, thereby setting the variable to <code>3</code>. It is not permitted for either example to produce the result <code>6</code>. Note that both of these examples have unspecified behavior in C, according to the ANSI/ISO standard.<p>
<a name="264262"></a>
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.<p>
<a name="18857"></a>
Thus, the test program:<p>
<blockquote><pre>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!");
       }
}
</pre></blockquote><a name="18858"></a>
prints:<p>
<blockquote><pre>java.lang.Exception: I'm outta here!
Now j = 1
</pre></blockquote><a name="264267"></a>
That is, the left-hand operand <code>forgetIt()</code> of the operator <code>/</code> throws an exception before the right-hand operand is evaluated and its embedded assignment of <code>2</code> to <code>j</code> occurs.<p>
<a name="18740"></a>
<h3>15.7.2    Evaluate Operands before Operation</h3>
<a name="18749"></a>
The Java programming language also guarantees that every operand of an operator (except the conditional operators <code>&amp;&amp;</code>, <code>||</code>, and <code>?</code> <code>:</code>) appears to be fully evaluated before any part of the operation itself is performed.<p>
<a name="264272"></a>
If the binary operator is an integer division <code>/</code> <a href="expressions.doc.html#5047">(&#167;15.17.2)</a> or integer remainder <code>%</code> <a href="expressions.doc.html#24956">(&#167;15.17.3)</a>, then its execution may raise an <code>ArithmeticException</code>, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.<p>
<a name="36160"></a>
So, for example, the program:<p>
<blockquote><pre>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!");
       }
}
</pre></blockquote><a name="36174"></a>
always prints:<p>
<blockquote><pre>java.lang.Exception: Shuffle off to Buffalo!
</pre></blockquote><a name="36176"></a>
and not:<p>
<blockquote><pre>java.lang.ArithmeticException: / by zero
</pre></blockquote><a name="264277"></a>
since no part of the division operation, including signaling of a divide-by-zero exception, may appear to occur before the invocation of <code>loseBig</code> 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.<p>
<a name="23213"></a>
<h3>15.7.3    Evaluation Respects Parentheses and Precedence</h3>
<a name="23217"></a>
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 <a href="memory.doc.html#26250">&#167;17</a>), for all possible computational values that might be involved.<p>
<a name="23218"></a>
In the case of floating-point calculations, this rule applies also for infinity and not-a-number (NaN) values. For example, <code>!(x&lt;y)</code> may not be rewritten as <code>x&gt;=y</code>, because these expressions have different values if either <code>x</code> or <code>y</code> is NaN or both are NaN.<p>
<a name="264283"></a>
Specifically, floating-point calculations that appear to be mathematically associative are unlikely to be computationally associative. Such computations must not be naively reordered. <p>
<a name="264281"></a>
For example, it is not correct for a Java compiler to rewrite <code>4.0*x*0.5</code> as <code>2.0*x</code>; while roundoff happens not to be an issue here, there are large values of <code>x</code> for which the first expression produces infinity (because of overflow) but the second expression produces a finite result.<p>
<a name="238102"></a>
So, for example, the test program:<p>
<blockquote><pre>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);
       }
}
</pre></blockquote><a name="23231"></a>
prints:<p>
<blockquote><pre>Infinity
1.6e+308
</pre></blockquote><a name="264288"></a>
because the first expression overflows and the second does not.<p>
<a name="264295"></a>
In contrast, integer addition and multiplication <em>are</em> provably associative in the Java programming language.<p>
<a name="264300"></a>
For example <code>a+b+c</code>, where <code>a</code>, <code>b</code>, and <code>c</code> are local variables (this simplifying assumption avoids issues involving multiple threads and <code>volatile</code> variables), will always produce the same answer whether evaluated as <code>(a+b)+c</code> or <code>a+(b+c)</code>; if the expression <code>b+c</code> occurs nearby in the code, a smart compiler may be able to use this common subexpression.<p>
<a name="23789"></a>
<h3>15.7.4    Argument Lists are Evaluated Left-to-Right</h3>
<a name="264305"></a>
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.<p>
<a name="23791"></a>
Thus:<p>
<blockquote><pre>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);
       }
}
</pre></blockquote><a name="23800"></a>
always prints:<p>
<blockquote><pre>going, going, gone
</pre></blockquote><a name="264310"></a>
because the assignment of the string <code>"gone"</code> to <code>s</code> occurs after the first two arguments to <code>print3</code> have been evaluated.<p>
<a name="264315"></a>
If evaluation of an argument expression completes abruptly, no part of any argument expression to its right appears to have been evaluated.<p>
<a name="23804"></a>
Thus, the example:<p>
<blockquote><pre>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;
       }
}
</pre></blockquote><a name="23821"></a>
prints:<p>
<blockquote><pre>java.lang.Exception: oops, id=1
</pre></blockquote><a name="264320"></a>
because the assignment of <code>3</code> to <code>id</code> is not executed.<p>
<a name="23451"></a>
<h3>15.7.5    Evaluation Order for Other Expressions</h3>
<a name="23452"></a>
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:<p>
<ul><a name="249837"></a>
<li>class instance creation expressions <a href="expressions.doc.html#251881">(&#167;15.9.4)</a>
<a name="249842"></a>
<li>array creation expressions <a href="expressions.doc.html#23605">(&#167;15.10.1)</a>
<a name="249846"></a>
<li>method invocation expressions <a href="expressions.doc.html#45677">(&#167;15.12.4)</a>
<a name="23491"></a>
<li>array access expressions <a href="expressions.doc.html#23958">(&#167;15.13.1)</a>
<a name="240795"></a>
<li>assignments involving array components <a href="expressions.doc.html#5281">(&#167;15.26)</a>
</ul><a name="23302"></a>
<h2>15.8    Primary Expressions</h2>
<a name="36225"></a>
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.<p>
<ul><pre>
<em>Primary:
       PrimaryNoNewArray
       ArrayCreationExpression

PrimaryNoNewArray:
       Literal
       Type . class
</em>   void</em> . class
       this
       ClassName.this
       ( Expression )
       ClassInstanceCreationExpression
       FieldAccess
       MethodInvocation
       ArrayAccess
</em></pre></ul><a name="224125"></a>
<h3>15.8.1    Lexical Literals</h3>
<a name="36407"></a>
A literal <a href="lexical.doc.html#48272">(&#167;3.10)</a> denotes a fixed, unchanging value.<p>
<a name="36387"></a>
The following production from <a href="lexical.doc.html#48272">&#167;3.10</a> is repeated here for convenience:<p>
<ul><pre>
<em>Literal:
       IntegerLiteral
       FloatingPointLiteral
       BooleanLiteral
       CharacterLiteral
       StringLiteral
       NullLiteral
</em></pre></ul><a name="36400"></a>
The type of a literal is determined as follows:<p>
<ul><a name="43814"></a>
<li>The type of an integer literal that ends with <code>L</code> or <code>l</code> is <code>long</code>; the type of any other integer literal is <code>int</code>.
<a name="251041"></a>
<li>The type of a floating-point literal that ends with <code>F</code> or <code>f</code> is <code>float</code> and its value must be an element of the float value set <a href="typesValues.doc.html#9208">(&#167;4.2.3)</a>. The type of any other floating-point literal is <code>double</code> and its value must be an element of the double value set.
<a name="36429"></a>
<li>The type of a boolean literal is <code>boolean</code>.
<a name="36436"></a>
<li>The type of a character literal is <code>char</code>.
<a name="36437"></a>
<li>The type of a string literal is <code>String</code>.
<a name="250692"></a>
<li>The type of the null literal <code>null</code> is the null type; its value is the null reference.
</ul><a name="250775"></a>
Evaluation of a lexical literal always completes normally.<p>
<a name="251530"></a>
<h3>15.8.2    Class Literals </h3>
<a name="250782"></a>
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. <p>
<a name="251519"></a>
<h3>15.8.3    <code>this</code> </h3>
<a name="251520"></a>
The keyword <code>this</code> 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.<p>
<a name="264342"></a>
When used as a primary expression, the keyword <code>this</code> denotes a value, that is a reference to the object for which the instance method was invoked <a href="expressions.doc.html#20448">(&#167;15.12)</a>, or to the object being constructed. The type of <code>this</code> is the class <i>C</i> within which the keyword <code>this</code> occurs. At run time, the class of the actual object referred to may be the class <i>C</i> or any subclass of <i>C</i>.<p>
<a name="31984"></a>
In the example:<p>
<blockquote><pre>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 &lt; v.length; i++)
                       if (v[i] != other.v[i])
                               return false;
               return true;
       }
}
</pre></blockquote><a name="264347"></a>
the class <code>IntVector</code> implements a method <code>equals</code>, which compares two vectors. If the <code>other</code> vector is the same vector object as the one for which the <code>equals</code> method was invoked, then the check can skip the length and value comparisons. The <code>equals</code> method implements this check by comparing the reference to the <code>other</code> object to <code>this</code>.<p>
<a name="20077"></a>
The keyword <code>this</code> is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body <a href="classes.doc.html#78435">(&#167;8.8.5)</a>.<p>
<a name="251603"></a>
<h3>15.8.4    Qualified <code>this</code></h3>
<a name="250907"></a>
Any lexically enclosing instance can be referred to by explicitly qualifying the keyword <code>this</code>.<p>
<a name="250970"></a>
Let <i>C</i> be the class denoted by <i>ClassName</i>. Let <i>n</i> be an integer such that <i>C</i> is the <i>n</i>th lexically enclosing class of the class in which the qualified this expression appears. The value of an expression of the form <i>ClassName</i>.<code>this</code> is the <i>n</i>th lexically enclosing instance of <code>this</code> <a href="classes.doc.html#262890">(&#167;8.1.2)</a>. The type of the expression is <i>C</i>. It is a compile-time error if the current class is not an inner class of class <i>C</i> or <i>C</i> itself.<p>
<a name="236822"></a>
<h3>15.8.5    Parenthesized Expressions</h3>
<a name="236823"></a>
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. <p>
<a name="249265"></a>
Parentheses do not affect in any way the choice of value set <a href="typesValues.doc.html#9208">(&#167;4.2.3)</a> for the value of an expression of type <code>float</code> or <code>double</code>.<p>
<a name="41147"></a>
<h2>15.9    Class Instance Creation Expressions</h2>
<a name="36595"></a>
A class instance creation expression is used to create new objects that are instances of classes.<p>
<ul><pre>
<i>ClassInstanceCreationExpression:
</i>    new<i> ClassOrInterfaceType ( ArgumentList<sub><i>opt</i></sub> ) ClassBodyopt
       Primary.new Identifier ( ArgumentListopt ) ClassBodyopt

ArgumentList:
       Expression
       ArgumentList , Expression
</i></pre></ul><a name="252035"></a>
Class instance creation expressions have two forms: <p>
<ul><a name="253146"></a>
<li><i>Unqualified class instance creation expressions</i> begin with the keyword <code>new</code>. An unqualified class instance creation expression may be used to create an instance of a class, regardless of whether the class is a top-level <a href="packages.doc.html#26783">(&#167;7.6)</a>, member (<a href="classes.doc.html#246026">&#167;8.5</a>, <a href="interfaces.doc.html#252566">&#167;9.5</a>), local <a href="statements.doc.html#247766">(&#167;14.3)</a> or anonymous class <a href="expressions.doc.html#252986">(&#167;15.9.5)</a>.
<a name="253111"></a>
<li><i>Qualified class instance creation expressions</i> begin with a <i>Primary</i>. A qualified class instance creation expression enables the creation of instances of inner member classes and their anonymous subclasses.
</ul><a name="252044"></a>
Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an <i>anonymous class</i> <a href="expressions.doc.html#252986">(&#167;15.9.5)</a> and creates an instance of it. <p>
<a name="253411"></a>
We say that a class is <i>instantiated</i> 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.<p>
<a name="23745"></a>
<h3>15.9.1    Determining the Class being Instantiated</h3>
<a name="253090"></a>
If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:<p>
<ul><a name="253179"></a>
<li>If the class instance creation expression is an unqualified class instance creation expression, then let <i>T</i> be the <i>ClassOrInterfaceType</i> after the new token. It is a compile-time error if the class or interface named by <i>T</i> is not accessible <a href="names.doc.html#104285">(&#167;6.6)</a>. If <i>T</i> is the name of a class, then an anonymous direct subclass of the class named by <i>T</i> is declared. It is a compile-time error if the class named by <i>T</i> is a <code>final</code> class. If <i>T</i> is the name of an interface then an anonymous direct subclass of <code>Object</code> that implements the interface named by <i>T</i> is declared. In either case, the body of the subclass is the <i>ClassBody</i> given in the class instance creation expression. The class being instantiated is the anonymous subclass.
<a name="253194"></a>
<li>Otherwise, the class instance creation expression is a qualified class instance creation expression. Let <i>T</i> be the name of the <i>Identifier</i> after the new token. It is a compile-time error if <i>T</i> is not the simple name <a href="names.doc.html#31692">(&#167;6.2)</a> of an accessible <a href="names.doc.html#104285">(&#167;6.6)</a> non-<code>final</code> inner class <a href="classes.doc.html#262890">(&#167;8.1.2)</a> that is a member of the compile-time type of the <i>Primary</i>. It is also a compile-time error if <i>T</i> is ambiguous <a href="classes.doc.html#246026">(&#167;8.5)</a>. An anonymous direct subclass of the class named by <i>T</i> is declared. The body of the subclass is the <i>ClassBody</i> given in the class instance creation expression. The class being instantiated is the anonymous subclass.
</ul><a name="253236"></a>
If a class instance creation expression does not declare an anonymous class, then:<p>
<ul><a name="253239"></a>
<li>If the class instance creation expression is an unqualified class instance creation expression, then the <em>ClassOrInterfaceType </em>must name a class that is accessible <a href="names.doc.html#104285">(&#167;6.6)</a> and not <code>abstract</code>, or a compile-time error occurs. In this case, the class being instantiated is the class denoted by ClassOrInterfaceType.
<a name="253242"></a>
<li>Otherwise, the class instance creation expression is a qualified class instance creation expression. It is a compile-time error if <i>Identifier</i> is not the simple name <a href="names.doc.html#31692">(&#167;6.2)</a> of an accessible <a href="names.doc.html#104285">(&#167;6.6)</a> non-<code>abstract</code> inner class <a href="classes.doc.html#262890">(&#167;8.1.2)</a> T that is a member of the compile-time type of the <i>Primary</i>. It is also a compile-time error if <i>Identifier</i> is ambiguous <a href="classes.doc.html#246026">(&#167;8.5)</a>. The class being instantiated is the class denoted by <i>Identifier</i>.
</ul><a name="253435"></a>
The type of the class instance creation expression is the class type being instantiated.<p>
<a name="253028"></a>
<h3>15.9.2    Determining Enclosing Instances</h3>
<a name="253034"></a>
Let <i>C</i> be the class being instantiated, and let <i>i</i> the instance being created. If <i>C</i> is an inner class then <i>i</i> may have an immediately enclosing instance. The immediately enclosing instance of <i>i</i> <a href="classes.doc.html#262890">(&#167;8.1.2)</a> is determined as follows:<p>
<ul><a name="253038"></a>
<li>If <i>C</i> is an anonymous class, then:
<ul>
<a name="254032"></a>
<li>If the class instance creation expression occurs in a static context <a href="classes.doc.html#262890">(&#167;8.1.2)</a>, then <i>i</i> has no immediately enclosing instance.
<a name="254034"></a>
<li>Otherwise, the immediately enclosing instance of <i>i</i> is <code>this</code>.
</ul>
<a name="254064"></a>
<li>If <i>C</i> is a local class <a href="statements.doc.html#247766">(&#167;14.3)</a>, <i>C</i> must be declared in a method declared in a lexically enclosing class <i>O</i>. Let <i>n</i> be an integer such that <i>O</i> is the <i>n</i>th lexically enclosing class of the class in which the class instance creation expression appears. Then:
<ul>
<a name="254067"></a>
<li>If <i>C</i> occurs in a static context, then <i>i</i> has no immediately enclosing instance.
<a name="267182"></a>
<li>Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.
<a name="254059"></a>
<li>Otherwise, the immediately enclosing instance of <i>i</i> is the <I>n</i>th lexically enclosing instance of <code>this </code><a href="classes.doc.html#262890">(&#167;8.1.2)</a>.
</ul>
<a name="253336"></a>
<li>Otherwise, <i>C</i> is an inner member class <a href="classes.doc.html#246026">(&#167;8.5)</a>.
<ul>
<a name="253064"></a>
<li>If the class instance creation expression is an unqualified class instance creation expression, then:
<ul>
<a name="253350"></a>
<li>If the class instance creation expression occurs in a static context, then a compile-time error occurs.
<a name="254073"></a>
<li>Otherwise, if <i>C</i> is a member of an enclosing class then let <i>O</i> be the innermost lexically enclosing class of which <i>C</i> is a member, and let <i>n</i> be an integer such that <i>O</i> is the <i>n</i>th lexically enclosing class of the class in which the class instance creation expression appears. The immediately enclosing instance of <i>i</i> is the <i>n</i>th lexically enclosing instance of <code>this.</code>
<a name="253408"></a>
<li>Otherwise, a compile-time error occurs.
</ul>
<a name="253340"></a>
<li>Otherwise, the class instance creation expression is a qualified class instance creation expression. The immediately enclosing instance of <i>i</i> is the object that is the value of the <i>Primary</i> expression.
</ul>
</ul><a name="253300"></a>
In addition, if <i>C</i> is an anonymous class, and the direct superclass of <i>C</i>, <i>S</i>, is an inner class then <i>i</i> may have an immediately enclosing instance with respect to <i>S</i> which is determined as follows:<p>
<ul><a name="253304"></a>
<li>If <i>S</i> is a local class <a href="statements.doc.html#247766">(&#167;14.3)</a>, then <i>S</i> must be declared in a method declared in a lexically enclosing class <i>O</i>. Let <i>n</i> be an integer such that <i>O</i> is the <i>n</i>th lexically enclosing class of the class in which the class instance creation expression appears. Then:
<ul>
<a name="267205"></a>
<li>If <i>S</i> occurs within a static context, then <i>i</i> has no immediately enclosing instance with respect to <i>S</i>.
<a name="267208"></a>
<li>Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.
<a name="254087"></a>
<li>Otherwise, the immediately enclosing instance of <i>i</i> with respect to <i>S</i> is the <i>n</i>th lexically enclosing instance of <code>this.</code>
</ul>
<a name="253365"></a>
<li>Otherwise, <i>S</i> is an inner member class <a href="classes.doc.html#246026">(&#167;8.5)</a>.
<ul>
<a name="253366"></a>
<li>If the class instance creation expression is an unqualified class instance creation expression, then:
<ul>
<a name="253367"></a>
<li>If the class instance creation expression occurs in a static context, then a compile-time error occurs.
<a name="254096"></a>
<li>Otherwise, if <i>S</i> is a member of an enclosing class then let <i>O</i> be the innermost lexically enclosing class of which <i>S</i> is a member, and let <i>n</i> be an integer such that <i>O</i> is the <i>n</i>th lexically enclosing class of the class in which the class instance creation expression appears. The immediately enclosing instance of <i>i</i> with respect to <i>S</i> is the <i>n</i>th lexically enclosing instance of <code>this.</code>
<a name="253368"></a>
<li>Otherwise, a compile-time error occurs.
</ul>
<a name="253369"></a>
<li>Otherwise, the class instance creation expression is a qualified class instance creation expression. The immediately enclosing instance of <i>i</i> with respect to <i>S</i> is the object that is the value of the <i>Primary</i> expression.
</ul>
</ul><a name="253029"></a>
<h3>15.9.3    Choosing the Constructor and its Arguments</h3>
<a name="253097"></a>
Let <i>C</i> be the class type being instantiated. To create an instance of <i>C</i>, <i>i</i>, a constructor of <i>C</i> is chosen at compile-time by the following rules:<p>
<ul><a name="253098"></a>
<li>First, the actual arguments to the constructor invocation are determined.
<ul>
<a name="253099"></a>
<li>If <i>C</i> is an anonymous class, and the direct superclass of <i>C</i>, <i>S</i>, is an inner class, then:
<ul>
<a name="254143"></a>
<li>If the <i>S</i> is a local class and <i>S</i> occurs in a static context, then the arguments in the argument list, if any, are the arguments to the constructor, in the order they appear in the expression.
<a name="254144"></a>
<li>Otherwise, the immediately enclosing instance of <i>i</i> with respect to <i>S</i> is the first argument to the constructor, followed by the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the expression.
</ul>
<a name="253100"></a>
<li>Otherwise the arguments in the argument list, if any, are the arguments to the constructor, in the order they appear in the expression.
</ul>
<a name="253101"></a>
<li>Once the actual arguments have been determined, they are used to select a constructor of <i>C</i>, using the same rules as for method invocations <a href="expressions.doc.html#20448">(&#167;15.12)</a>. As in method invocations, a compile-time method matching error results if there is no unique most-specific constructor that is both applicable and accessible.
</ul><a name="253105"></a>
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.<p>
<a name="251881"></a>
<h3>15.9.4    Run-time Evaluation of Class Instance Creation Expressions</h3>
<a name="36655"></a>
At run time, evaluation of a class instance creation expression is as follows.<p>
<a name="265442"></a>
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 <code>null</code>, a <code>NullPointerException</code> 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.<p>
<a name="23746"></a>
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 <code>OutOfMemoryError</code> <a href="expressions.doc.html#36687">(&#167;15.9.6)</a>.<p>
<a name="23753"></a>
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 <a href="typesValues.doc.html#96595">(&#167;4.5.5)</a>.<p>
<a name="36584"></a>
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.<p>
<a name="36513"></a>
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 <a href="classes.doc.html#41652">(&#167;8.8)</a> and is described in detail in <a href="execution.doc.html#44670">&#167;12.5</a>.<p>
<a name="23747"></a>
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.<p>
<a name="252986"></a>
<h3>15.9.5    Anonymous Class Declarations</h3>
<a name="252987"></a>
An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.<p>
<a name="252992"></a>
An anonymous class is never <code>abstract</code> <a href="classes.doc.html#34944">(&#167;8.1.1.1)</a>. An anonymous class is always an inner class <a href="classes.doc.html#262890">(&#167;8.1.2)</a>; it is never <code>static</code> (<a href="classes.doc.html#21613">&#167;8.1.1</a>, <a href="classes.doc.html#246853">&#167;8.5.2</a>). An anonymous class is always implicitly <code>final</code> <a href="classes.doc.html#54727">(&#167;8.1.1.2)</a>.<p>
<a name="253002"></a>
<h4>15.9.5.1    Anonymous Constructors</h4>
<a name="253003"></a>
An anonymous class cannot have an explicitly declared constructor. Instead, the compiler must automatically provide an <i>anonymous constructor</i> for the anonymous class. The form of the anonymous constructor of an anonymous class <i>C</i> with direct superclass <i>S</i> is as follows:<p>
<ul><a name="253005"></a>
<li>If <i>S</i> is not an inner class, or if <i>S</i> is a local class that occurs in a static context, then the anonymous constructor has one formal parameter for each actual argument to the class instance creation expression in which <i>C</i> is declared. The actual arguments to the class instance creation expression are used to determine a constructor <i>cs</i> of <i>S</i>, using the same rules as for method invocations <a href="expressions.doc.html#20448">(&#167;15.12)</a>. The type of each formal parameter of the anonymous constructor must be identical to the corresponding formal parameter of <i>cs</i>.
<a name="290200"></a>
The body of the constructor consists of an explicit constructor invocation <a href="classes.doc.html#229267">(&#167;8.8.5.1)</a> of the form <code>super</code>(...), where the actual arguments are the formal parameters of the constructor, in the order they were declared.<p>
<a name="253006"></a>
<li>Otherwise, the first formal parameter of the constructor of <i>C</i> represents the value of the immediately enclosing instance of <i>i</i> with respect to <i>S</i>. The type of this parameter is the class type that immediately encloses the declaration of <i>S</i>. The constructor has an additional formal parameter for each actual argument to the class instance creation expression that declared the anonymous class. The <i>n</i>th formal parameter <i>e</i> corresponds to the <i>n</i> - 1st actual argument. The actual arguments to the class instance creation expression are used to determine a constructor <i>cs</i> of <i>S</i>, using the same rules as for method invocations <a href="expressions.doc.html#20448">(&#167;15.12)</a>. The type of each formal parameter of the anonymous constructor must be identical to the corresponding formal parameter of <i>cs</i>. The body of the constructor consists of an explicit constructor invocation <a href="classes.doc.html#229267">(&#167;8.8.5.1)</a> of the form <i>o</i>.<code>super</code>(...), where <i>o</i> is the first formal parameter of the constructor, and the actual arguments are the subsequent formal parameters of the constructor, in the order they were declared.
</ul><a name="264352"></a>
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.<p>
<a name="289502"></a>
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 <i>cs</i>). This does not, in itself, cause any errors at either compile time or run time.<p>
<a name="36687"></a>
<h3>15.9.6    Example: Evaluation Order and Out-of-Memory Detection</h3>
<a name="36695"></a>
If evaluation of a class instance creation expression finds there is insufficient memory to perform the creation operation, then an <code>OutOfMemoryError</code> is thrown. This check occurs before any argument expressions are evaluated.<p>
<a name="36696"></a>
So, for example, the test program:<p>
<blockquote><pre>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));
               }
       }
}
</pre></blockquote><a name="36716"></a>
prints:<p>
<blockquote><pre>java.lang.OutOfMemoryError: List, false
</pre></blockquote><a name="36788"></a>
because the out-or-memory condition is detected before the argument expression <code>oldid</code> <code>=</code> <code>id</code> is evaluated.<p>
<a name="264357"></a>
Compare this to the treatment of array creation expressions <a href="expressions.doc.html#46168">(&#167;15.10)</a>, for which the out-of-memory condition is detected after evaluation of the dimension expressions <a href="expressions.doc.html#36736">(&#167;15.10.3)</a>.<p>
<a name="46168"></a>
<h2>15.10    Array Creation Expressions</h2>
<a name="46169"></a>
An array instance creation expression is used to create new arrays <a href="arrays.doc.html#27803">(&#167;10)</a>.<p>
<ul><pre>
<em>ArrayCreationExpression:
       </em>new<em> PrimitiveType DimExprs Dims<sub><i>opt
       </i></sub></em>new<em> TypeName DimExprs Dims<sub><i>opt
</i></sub>      </em>new<em> PrimitiveType Dims ArrayInitializer
       </em>new<em> TypeName Dims ArrayInitializer
</em></pre></ul><a name="250757"></a>
<p>
<ul><pre>
<em>DimExprs:
       DimExpr
       DimExprs DimExpr

DimExpr:
       </em>[<em> Expression</em> ]<em>

Dims:
       </em>[ ]<em>
       Dims </em>[ ]
</pre></ul><a name="224310"></a>
An array creation expression creates an object that is a new array whose elements are of the type specified by the <em>PrimitiveType</em> or <em>TypeName</em>. The <em>TypeName</em> may name any named reference type, even an <code>abstract</code> class type <a href="classes.doc.html#34944">(&#167;8.1.1.1)</a> or an interface type <a href="interfaces.doc.html#238678">(&#167;9)</a>.<p>
<a name="264364"></a>
The type of the creation expression is an array type that can denoted by a copy of the creation expression from which the <code>new</code> keyword and every <em>DimExpr</em> expression and array initializer have been deleted.<p>
<a name="264361"></a>
For example, the type of the creation expression:<p>
<blockquote><pre>new double[3][3][]
</pre></blockquote><a name="224312"></a>
is:<p>
<blockquote><pre>double[][][]
</pre></blockquote><a name="23548"></a>
The type of each dimension expression within a <em>DimExpr</em> must be an integral type, or a compile-time error occurs. Each expression undergoes unary numeric promotion <a href="conversions.doc.html#170952">(&#167;5.6.1)</a>. The promoted type must be <code>int</code>, or a compile-time error occurs; this means, specifically, that the type of a dimension expression must not be <code>long</code>.<p>
<a name="260981"></a>
If an array initializer is provided, the newly allocated array will be initialized with the values provided by the array initializer as described in <a href="arrays.doc.html#11358">&#167;10.6</a>.<p>
<a name="23605"></a>
<h3>15.10.1    Run-time Evaluation of Array Creation Expressions</h3>
<a name="36668"></a>
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:<p>
<a name="23552"></a>
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.<p>
<a name="23543"></a>
Next, the values of the dimension expressions are checked. If the value of any <em>DimExpr</em> expression is less than zero, then an <code>NegativeArraySizeException</code> is thrown.<p>
<a name="36922"></a>
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 <code>OutOfMemoryError</code>.<p>
<a name="23658"></a>
Then, if a single <em>DimExpr</em> appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value <a href="typesValues.doc.html#96595">(&#167;4.5.5)</a>.<p>
<a name="264375"></a>
If an array creation expression contains <em>N</em> <em>DimExpr</em> expressions, then it effectively executes a set of nested loops of depth <em>N</em> - 1 to create the implied arrays of arrays. <p>
<a name="264373"></a>
For example, the declaration:<p>
<blockquote><pre><code>float[][] matrix = new float[3][3];
</code></pre></blockquote><a name="23642"></a>
is equivalent in behavior to:<p>
<blockquote><pre>float[][] matrix = new float[3][];
for (int <em>d</em> = 0; <em>d</em> &lt; matrix.length; <em>d</em>++)
       matrix[<em>d</em>] = new float[3];
</pre></blockquote><a name="23645"></a>
and:<p>
<blockquote><pre>Age[][][][][] Aquarius = new Age[6][10][8][12][];
</pre></blockquote><a name="23647"></a>
is equivalent to:<p>
<blockquote><pre>Age[][][][][] Aquarius = new Age[6][][][][];
for (int <em>d1</em> = 0; <em>d1</em> &lt; Aquarius.length; <em>d1</em>++) {
       Aquarius[<em>d1</em>] = new Age[10][][][];
       for (int <em>d2</em> = 0; <em>d2</em> &lt; Aquarius[<em>d1</em>].length; <em>d2</em>++) {
               Aquarius[<em>d1</em>][<em>d2</em>] = new Age[8][][];
               for (int <em>d3</em> = 0; <em>d3</em> &lt; Aquarius[<em>d1</em>][<em>d2</em>].length; <em>d3</em>++) {
                       Aquarius[<em>d1</em>][<em>d2</em>][<em>d3</em>] = new Age[12][];
               }
       }
}
</pre></blockquote><a name="36995"></a>
with <i>d,</i> <i>d1</i>, <i>d2</i> and <i>d3</i> replaced by names that are not already locally declared. Thus, a single <code>new</code> 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 <code>Age</code> objects), initialized only to null references. These arrays can be filled in later by other code, such as:<p>
<blockquote><pre>Age[] Hair = { new Age("quartz"), new Age("topaz") };
Aquarius[1][9][6][9] = Hair;
<a name="264386"></a>
A multidimensional array need not have arrays of the same length at each level. <p>
<a name="264384"></a>
Thus, a triangular matrix may be created by:<p>
float triang[][] = new float[100][];
for (int i = 0; i &lt; triang.length; i++)
       triang[i] = new float[i+1];
</pre></blockquote><a name="286280"></a>
<h3>15.10.2    Example: Array Creation Evaluation Order</h3>
<a name="264396"></a>
In an array creation expression <a href="expressions.doc.html#46168">(&#167;15.10)</a>, 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.<p>
<a name="23510"></a>
Thus:<p>
<blockquote><pre>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 + "]");
       }
}
</pre></blockquote><a name="23519"></a>
prints:<p>
<blockquote><pre>[4,3]
</pre></blockquote><a name="23521"></a>
because the first dimension is calculated as <code>4</code> before the second dimension expression sets <code>i</code> to <code>3</code>.<p>
<a name="23522"></a>
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: <p>
<blockquote><pre>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");
       }
}
</pre></blockquote><a name="23536"></a>
prints:<p>
<blockquote><pre>java.lang.Exception: unimplemented, i=99
</pre></blockquote><a name="23538"></a>
because the embedded assignment that sets <code>i</code> to <code>1</code> is never executed.<p>
<a name="36736"></a>
<h3>15.10.3    Example: Array Creation and Out-of-Memory Detection</h3>
<a name="36885"></a>
If evaluation of an array creation expression finds there is insufficient memory to perform the creation operation, then an <code>OutOfMemoryError</code> is thrown. This check occurs only after evaluation of all dimension expressions has completed normally. <p>
<a name="36744"></a>
So, for example, the test program:<p>
<blockquote><pre>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));
               }
       }
}
</pre></blockquote><a name="36764"></a>
prints:<p>
<blockquote><pre>java.lang.OutOfMemoryError, true
</pre></blockquote><a name="36901"></a>
because the out-of-memory condition is detected after the dimension expression <code>oldlen</code> = <code>len</code> is evaluated.<p>
<a name="264401"></a>
Compare this to class instance creation expressions <a href="expressions.doc.html#41147">(&#167;15.9)</a>, which detect the out-of-memory condition before evaluating argument expressions <a href="expressions.doc.html#36687">(&#167;15.9.6)</a>.<p>
<a name="41267"></a>
<h2>15.11    Field Access Expressions</h2>
<a name="37024"></a>
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 <code>super</code>. (It is also possible to refer to a field of the current instance or current class by using a simple name; see <a href="names.doc.html#21650">&#167;6.5.6</a>.)<p>
<ul><pre>
<em>FieldAccess:
       Primary . Identifier
       </em>super<em> . Identifier
       ClassName .</em>super<em> . Identifier
</em></pre></ul><a name="37051"></a>
The meaning of a field access expression is determined using the same rules as for qualified names <a href="names.doc.html#104285">(&#167;6.6)</a>, but limited by the fact that an expression cannot denote a package, class type, or interface type.<p>
<a name="37055"></a>
<h3>15.11.1    Field Access Using a Primary</h3>
<a name="37056"></a>
The type of the <em>Primary</em> must be a reference type <i>T</i>, or a compile-time error occurs. The meaning of the field access expression is determined as follows:<p>
<ul><a name="20394"></a>
<li>If the identifier names several accessible member fields of type <i>T</i>, then the field access is ambiguous and a compile-time error occurs.
<a name="37075"></a>
<li>If the identifier does not name an accessible member field of type <i>T</i>, then the field access is undefined and a compile-time error occurs.
<a name="20398"></a>
<li>Otherwise, the identifier names a single accessible member field of type <i>T</i> and the type of the field access expression is the declared type of the field. At run time, the result of the field access expression is computed as follows:
<ul>
<a name="37316"></a>
<li>If the field is <code>static</code>:
<ul>
<a name="37335"></a>
<li>If the field is <code>final</code>, then the result is the value of the specified class variable in the class or interface that is the type of the <em>Primary</em> expression.
<a name="37336"></a>
<li>If the field is not <code>final</code>, then the result is a variable, namely, the specified class variable in the class that is the type of the <em>Primary</em> expression.
</ul>
<a name="37320"></a>
<li>If the field is not <code>static</code>:
<ul>
<a name="37110"></a>
<li>If the value of the <em>Primary</em> is <code>null</code>, then a <code>NullPointerException</code> is thrown.
<a name="20427"></a>
<li>If the field is <code>final</code>, then the result is the value of the specified instance variable in the object referenced by the value of the <em>Primary</em>.
<a name="264406"></a>
<li>If the field is not <code>final</code>, then the result is a variable, namely, the specified instance variable in the object referenced by the value of the <em>Primary</em>.
</ul>
</ul>
</ul><a name="37135"></a>
Note, specifically, that only the type of the <em>Primary</em> expression, not the class of the actual object referred to at run time, is used in determining which field to use.<p>
<a name="21262"></a>
Thus, the example:<p>
<blockquote><pre>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.";
       }
}
</pre></blockquote><a name="20906"></a>
produces the output:<p>
<blockquote><pre>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.
</pre></blockquote><a name="45446"></a>
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 <code>s</code> holds a reference to an object of class <code>T</code>, the expression <code>s.x</code> refers to the <code>x</code> field of class <code>S</code>, because the type of the expression <code>s</code> is <code>S</code>. Objects of class <code>T</code> contain two fields named <code>x</code>, one for class <code>T</code> and one for its superclass <code>S</code>.<p>
<a name="22264"></a>
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:<p>
<blockquote><pre>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.";
       }
}
</pre></blockquote><a name="238134"></a>
Now the output is:<p>
<blockquote><pre>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.
</pre></blockquote><a name="37254"></a>
The last line shows that, indeed, the method that is accessed <em>does</em> depend on the run-time class of referenced object; when <code>s</code> holds a reference to an object of class <code>T</code>, the expression <code>s.z()</code> refers to the <code>z</code> method of class <code>T</code>, despite the fact that the type of the expression <code>s</code> is <code>S</code>. Method <code>z</code> of class <code>T</code> overrides method <code>z</code> of class <code>S</code>.<p>
<a name="22234"></a>
The following example demonstrates that a null reference may be used to access a class (<code>static</code>) variable without causing an exception:<p>
<blockquote><pre>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);
       }
}
</pre></blockquote><a name="22242"></a>
It compiles, executes, and prints:<p>
<blockquote><pre>Mount Chocorua
</pre></blockquote>
<a name="264411"></a>
Even though the result of <code>favorite()</code> is <code>null</code>, a <code>NullPointerException</code> is <em>not</em> thrown. That "<code>Mount </code>" is printed demonstrates that the <em>Primary</em> 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 <code>mountain</code> is <code>static</code>).<p>
<a name="20860"></a>
<h3>15.11.2    Accessing Superclass Members using <code>super</code></h3>
<a name="20451"></a>
The special forms using the keyword <code>super</code> 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 <code>this</code> may be used <a href="expressions.doc.html#251519">(&#167;15.8.3)</a>. The forms involving <code>super</code> may not be used anywhere in the class <code>Object</code>, since <code>Object</code> has no superclass; if <code>super</code> appears in class <code>Object</code>, then a compile-time error results.<p>
<a name="264416"></a>
Suppose that a field access expression <code>super.</code><i>name</i> appears within class <i>C</i>, and the immediate superclass of <i>C</i> is class <i>S</i>. Then <code>super.</code><i>name</i> is treated exactly as if it had been the expression <code>((</code><i>S</i><code>)this).</code><i>name</i>; thus, it refers to the field named <i>name</i> of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named <i>name</i> that is visible in class <i>S</i>, even if that field is hidden by a declaration of a field named <i>name</i> in class <i>C</i>.<p>
<a name="20763"></a>
The use of <code>super</code> is demonstrated by the following example:<p>
<blockquote><pre>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();
       }
}
</pre></blockquote><a name="20520"></a>
which produces the output:<p>
<blockquote><pre>x=                                     3
super.x=                                        2
((T2)this).x=                                   2
((T1)this).x=                                   1
((I)this).x=                                    0
</pre></blockquote><a name="37491"></a>
Within class <code>T3</code>, the expression <code>super.x</code> is treated exactly as if it were:<p>
<blockquote><pre><code>((T2)this).x</code>
</pre></blockquote><a name="251555"></a>
Suppose that a field access expression <code>T.super</code>.<i>name</i> appears within class <i>C</i>, and the immediate superclass of the class denoted by <i>T</i> is a class whose fully qualified name is <i>S</i>. Then <code>T.super</code>.<i>name</i> is treated exactly as if it had been the expression ((<i>S</i>)<code>T.this</code>).<i>name</i>. <p>
<a name="253969"></a>
Thus the expression <code>T.super</code>.<i>name</i> can access the field named name that is visible in the class named by <i>S</i>, even if that field is hidden by a declaration of a field named name in the class named by <i>T</i>.<p>
<a name="253972"></a>
It is a compile-time error if the class denoted by <i>T </i>is not a lexically enclosing class of the current class.<p>
<a name="20448"></a>
<h2>15.12    Method Invocation Expressions</h2>
<a name="37518"></a>
A method invocation expression is used to invoke a class or instance method.<p>
<ul><pre>
<em>MethodInvocation:
       MethodName ( ArgumentList<sub><i>opt</i></sub> )
       Primary . Identifier ( ArgumentList<sub><i>opt</i></sub> )
       </em>super<em> . Identifier ( ArgumentList<sub><i>opt</i></sub> )
       ClassName .</em> super<em> . Identifier ( ArgumentList<sub>opt</sub> )
</em></pre></ul><a name="8506"></a>
The definition of <em>ArgumentList</em> from <a href="expressions.doc.html#41147">&#167;15.9</a> is repeated here for convenience:<p>
<ul><pre>
<em>ArgumentList:
       Expression
       ArgumentList , Expression
</em></pre></ul>
<a name="264431"></a>
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.<p>
</pre></ul><a name="38751"></a>
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 <a href="expressions.doc.html#23617">&#167;15.12.3</a>.<p>
<a name="21692"></a>
<h3>15.12.1    Compile-Time Step 1: Determine Class or Interface to Search</h3>
<a name="37532"></a>
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:<p>
<ul><a name="37552"></a>
<li>If the form is <em>MethodName</em>, then there are three subcases:
<ul>
<a name="37575"></a>
<li>If it is a simple name, that is, just an <em>Identifier</em>, then the name of the method is the <em>Identifier</em>. If the <i>Identifier</i> appears within the scope <a href="names.doc.html#103228">(&#167;6.3)</a> of a visible method declaration with that name, then there must be an enclosing type declaration of which that method is a member. Let <i>T</i> be the innermost such type declaration. The class or interface to search is <i>T</i>.
<a name="37556"></a>
<li>If it is a qualified name of the form <em>TypeName</em> <code>.</code> <em>Identifier</em>, then the name of the method is the <em>Identifier</em> and the class to search is the one named by the <em>TypeName</em>. If <em>TypeName</em> is the name of an interface rather than a class, then a compile-time error occurs, because this form can invoke only <code>static</code> methods and interfaces have no <code>static</code> methods.
<a name="37591"></a>
<li>In all other cases, the qualified name has the form <em>FieldName</em> <code>.</code> <em>Identifier</em>; then the name of the method is the <em>Identifier</em> and the class or interface to search is the declared type of the field named by the <em>FieldName</em>.
</ul>
<a name="37589"></a>
<li>If the form is <em>Primary</em> <code>.</code> <em>Identifier</em>, then the name of the method is the <em>Identifier</em> &#32;and the class or interface to be searched is the type of the <em>Primary</em> expression.
<a name="37600"></a>
<li>If the form is <code>super</code> <code>.</code> <em>Identifier</em>, then the name of the method is the <em>Identifier</em> and the class to be searched is the superclass of the class whose declaration contains the method invocation. Let <i>T</i> be the type declaration immediately enclosing the method invocation. It is a compile-time error if any of the following situations occur:
<ul>
<a name="256960"></a>
<li><i>T</i> is the class <code>Object</code>.
<a name="289724"></a>
<li><i>T</i> is an interface.
</ul>
<a name="289785"></a>
<li>If the form is ClassName.super . Identifier, then the name of the method is the Identifier and the class to be searched is the superclass of the class C denoted by ClassName. It is a compile-time error if C is not a lexically enclosing class of the current class. It is a compile-time error if C is the class Object. Let T be the type declaration immediately enclosing the method invocation. It is a compile-time error if any of the following situations occur:
<ul>
<a name="256987"></a>
<li><i>T</i> is the class Object.
<a name="289900"></a>
<li><i>T</i> is an interface.
</ul>
</ul><a name="289905"></a>
<h3>15.12.2    Compile-Time Step 2: Determine Method Signature</h3>
<a name="19915"></a>
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 <em>applicable</em> and <em>accessible</em>, 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 <em>most specific</em> 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.<p>
<a name="18427"></a>
<h4>15.12.2.1    Find Methods that are Applicable and Accessible</h4>
<a name="21818"></a>
A method declaration is <em>applicable</em> to a method invocation if and only if both of the following are true:<p>
<ul><a name="37650"></a>
<li>The number of parameters in the method declaration equals the number of argument &#32;expressions in the method invocation.
<a name="37653"></a>
<li>The type of each actual argument can be converted by method invocation conversion <a href="conversions.doc.html#12687">(&#167;5.3)</a> to the type of the corresponding parameter. Method invocation conversion is the same as assignment conversion <a href="conversions.doc.html#184206">(&#167;5.2)</a>, except that constants of type <code>int</code> are never implicitly narrowed to <code>byte</code>, <code>short</code>, or <code>char</code>.
</ul><a name="21702"></a>
The class or interface determined by the process described in <a href="expressions.doc.html#21692">&#167;15.12.1</a> is searched for all method declarations applicable to this method invocation; method definitions inherited from superclasses and superinterfaces are included in this search.<p>
<a name="37690"></a>
Whether a method declaration is <em>accessible </em><a href="names.doc.html#104285">(&#167;6.6)</a> at a method invocation depends on the access modifier (<code>public</code>, none, <code>protected</code>, or <code>private</code>) in the method declaration and on where the method invocation appears.<p>
<a name="264456"></a>
If the class or interface has no method declaration that is both applicable and accessible, then a compile-time error occurs.<p>
<a name="37720"></a>
In the example program:<p>
<blockquote><pre>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
       }
}
</pre></blockquote><a name="37704"></a>
for the method invocation <code>two(1)</code> within class <code>Doubler</code>, there are two accessible methods named <code>two</code>, but only the second one is applicable, and so that is the one invoked at run time. For the method invocation <code>two(3)</code> within class <code>Test</code>, there are two applicable methods, but only the one in class <code>Test</code> is accessible, and so that is the one to be invoked at run time (the argument <code>3</code> is converted to type <code>long</code>). For the method invocation <code>Doubler.two(3)</code>, the class <code>Doubler</code>, not class <code>Test</code>, is searched for methods named <code>two</code>; the only applicable method is not accessible, and so this method invocation causes a compile-time error.<p>
<a name="21942"></a>
Another example is:<p>
<blockquote><pre>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
       }
}
</pre></blockquote><a name="21881"></a>
Here, a compile-time error occurs for the second invocation of <code>setColor</code>, because no applicable method can be found at compile time. The type of the literal <code>37</code> is <code>int</code>, and <code>int</code> cannot be converted to <code>byte</code> by method invocation conversion. Assignment conversion, which is used in the initialization of the variable <code>color</code>, performs an implicit conversion of the constant from type <code>int</code> to <code>byte</code>, which is permitted because the value <code>37</code> is small enough to be represented in type <code>byte</code>; but such a conversion is not allowed for method invocation conversion.<p>
<a name="21968"></a>
If the method <code>setColor</code> had, however, been declared to take an <code>int</code> instead of a <code>byte</code>, then both method invocations would be correct; the first invocation would be allowed because method invocation conversion does permit a widening conversion from <code>byte</code> to <code>int</code>. However, a narrowing cast would then be required in the body of <code>setColor</code>:<p>
<blockquote><pre>       void setColor(int color) { this.color = (byte)color; }
</pre></blockquote><a name="18428"></a>
<h4>15.12.2.2    Choose the Most Specific Method</h4>
<a name="272863"></a>
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 <em>most specific</em> method is chosen.<p>
<a name="272868"></a>
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.<p>
<a name="272869"></a>
The precise definition is as follows. Let <i>m</i> be a name and suppose that there are two declarations of methods named <i>m</i>, each having <i>n</i> parameters. Suppose that one declaration appears within a class or interface <i>T</i> and that the types of the parameters are <i>T1</i>,&#32;. . . ,&#32;<i>Tn</i>; suppose moreover that the other declaration appears within a class or interface <i>U</i> and that the types of the parameters are <i>U1</i>, . . . ,&#32;<i>Un</i>. Then the method <i>m</i> declared in <i>T</i> is <em>more specific</em> than the method <i>m</i> declared in <i>U</i> if and only if both of the following are true:<p>
<ul><a name="37872"></a>
<li><i>T</i> can be converted to <i>U</i> by method invocation conversion.
<a name="37876"></a>
<li><i>Tj</i> can be converted to <i>Uj</i> by method invocation conversion, for all <i>j</i> from <code>1</code> to <i>n</i>.
</ul><a name="37912"></a>
A method is said to be <em>maximally specific</em> for a method invocation if it is applicable and accessible and there is no other applicable and accessible method that is more specific.<p>
<a name="37937"></a>
If there is exactly one maximally specific method, then it is in fact <em>the most specific</em> 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 <a href="expressions.doc.html#23617">&#167;15.12.3</a>.<p>
<a name="264476"></a>
It is possible that no method is the most specific, because there are two or more maximally specific methods. In this case:<p>
<ul><a name="289532"></a>
<li>If all the maximally specific methods have the same signature, then:
<ul>
<a name="289533"></a>
<li>If one of the maximally specific methods is not declared <code>abstract</code>, it is the most specific method.
<a name="289534"></a>
<li>Otherwise, all the maximally specific methods are necessarily declared <code>abstract</code>. The most specific method is chosen arbitrarily among the maximally specific methods. However, the most specific method is considered to throw a checked exception if and only if that exception is declared in the <code>throws</code> clauses of each of the maximally specific methods.
</ul>
<a name="289531"></a>
<li>Otherwise, we say that the method invocation is <em>ambiguous</em>, and a compile-time error occurs.
</ul><a name="21711"></a>
<h4>15.12.2.3    Example: Overloading Ambiguity</h4>
<a name="21712"></a>
Consider the example:<p>
<blockquote><pre>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
       }
}
</pre></blockquote><a name="21726"></a>
This example produces an error at compile time. The problem is that there are two declarations of <code>test</code> that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous.<p>
<a name="38010"></a>
If a third definition of <code>test</code> were added:<p>
<blockquote><pre>       static void test(ColoredPoint p, ColoredPoint q) {
               System.out.println("(ColoredPoint, ColoredPoint)");
       }
</pre></blockquote><a name="38011"></a>
then it would be more specific than the other two, and the method invocation would no longer be ambiguous.<p>
<a name="21727"></a>
<h4>15.12.2.4    Example: Return Type Not Considered</h4>
<a name="21728"></a>
As another example, consider:<p>
<blockquote><pre>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
       }
}
</pre></blockquote><a name="21743"></a>
Here the most specific declaration of method <code>test</code> is the one taking a parameter of type <code>ColoredPoint</code>. Because the result type of the method is <code>int</code>, a compile-time error occurs because an <code>int</code> cannot be converted to a <code>String</code> by assignment conversion. This example shows that the result types of methods do not participate in resolving overloaded methods, so that the second <code>test</code> method, which returns a <code>String</code>, is not chosen, even though it has a result type that would allow the example program to compile without error.<p>
<a name="29775"></a>
<h4>15.12.2.5    Example: Compile-Time Resolution</h4>
<a name="30681"></a>
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.<p>
<a name="30687"></a>
So, for example, consider two compilation units, one for class <code>Point</code>:<p>
<blockquote><pre>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 + ")";
       }
}
</pre></blockquote><a name="30799"></a>
and one for class <code>ColoredPoint</code>:<p>
<blockquote><pre>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
                &#32; &#32;this <code>ColoredPoint</code> object. */
       public void adopt(Point p) { x = p.x; y = p.y; }
       public String toString() {
               String s = "," + COLORS[color];
               return super.toString(s);
       }
}
</pre></blockquote><a name="30815"></a>
Now consider a third compilation unit that uses <code>ColoredPoint</code>:<p>
<blockquote><pre>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);
       }
}
</pre></blockquote><a name="30754"></a>
The output is:<p>
<blockquote><pre>cp: (3,3,red)
</pre></blockquote>
<a name="30756"></a>
The application programmer who coded class <code>Test</code> has expected to see the word <code>green</code>, because the actual argument, a <code>ColoredPoint</code>, has a <code>color</code> field, and <code>color</code> would seem to be a "relevant field" (of course, the documentation for the package <code>Points</code> ought to have been much more precise!).<p>
<a name="38120"></a>
Notice, by the way, that the most specific method (indeed, the only applicable method) for the method invocation of <code>adopt</code> has a signature that indicates a method of one parameter, and the parameter is of type <code>Point</code>. This signature becomes part of the binary representation of class <code>Test</code> produced by the compiler and is used by the method invocation at run time.<p>
<a name="38098"></a>
Suppose the programmer reported this software error and the maintainer of the <code>points</code> package decided, after due deliberation, to correct it by adding a method to class <code>ColoredPoint</code>:<p>
<blockquote><pre>
public void adopt(ColoredPoint p) {
       adopt((Point)p); color = p.color;
}
</pre></blockquote>
<a name="239516"></a>
If the application programmer then runs the old binary file for <code>Test</code> with the new binary file for <code>ColoredPoint</code>, the output is still:<p>
<blockquote><pre>
cp: (3,3,red)
</pre></blockquote><a name="38138"></a>
because the old binary file for <code>Test</code> still has the descriptor "one parameter, whose type is <code>Point</code>; <code>void</code>" associated with the method call <code>cp.adopt(cp2)</code>. If the source code for <code>Test</code> is recompiled, the compiler will then discover that there are now two applicable <code>adopt</code> methods, and that the signature for the more specific one is "one parameter, whose type is <code>ColoredPoint</code>; <code>void</code>"; running the program will then produce the desired output:<p>
<blockquote><pre>cp: (3,3,green)
</pre></blockquote>
<a name="30865"></a>
With forethought about such problems, the maintainer of the <code>points</code> package could fix the <code>ColoredPoint</code> class to work with both newly compiled and old code, by adding defensive code to the old <code>adopt</code> method for the sake of old code that still invokes it on <code>ColoredPoint</code> arguments:<p>
<blockquote><pre>
public void adopt(Point p) {
       if (p instanceof ColoredPoint)
               color = ((ColoredPoint)p).color;
       x = p.x; y = p.y;
}
</pre></blockquote>
<a name="264481"></a>
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 <a href="binaryComp.doc.html#44871">&#167;13</a> for a detailed discussion of binary compatibility and type evolution.<p>
<a name="23617"></a>
<h3>15.12.3    Compile-Time Step 3: Is the Chosen Method Appropriate?</h3>
<a name="23618"></a>
If there is a most specific method declaration for a method invocation, it is called the <em>compile-time declaration</em> for the method invocation. Three further checks must be made on the compile-time declaration:<p>
<ul><a name="289578"></a>
<li>If the method invocation has, before the left parenthesis, a <em>MethodName</em> of the &#32;form <em>Identifier</em>, and the method is an instance method, then:
<ul>
<a name="289583"></a>
<li>If the invocation appears within a static context <a href="classes.doc.html#262890">(&#167;8.1.2)</a>, then a compile-time error occurs. (The reason is that a method invocation of this form cannot be used to invoke an instance method in places where <code>this</code> <a href="expressions.doc.html#251519">(&#167;15.8.3)</a> is not defined.)
<a name="289594"></a>
<li>Otherwise, let <i>C</i> be the innermost enclosing class of which the method is a member. If the invocation is not directly enclosed by <i>C</i> or an inner class of <i>C</i>, then a compile-time error occurs
</ul>
<a name="21464"></a>
<li>If the method invocation has, before the left parenthesis, a <em>MethodName</em> of the &#32;form <em>TypeName</em> <code>.</code> <em>Identifier</em>, then the compile-time declaration should be <code>static</code>. If the compile-time declaration for the method invocation is for an instance &#32;method, then a compile-time error occurs. (The reason is that a method invocation of this form does not specify a reference to an object that can serve as <code>this</code> within the instance method.)
<a name="289655"></a>
<li>If the method invocation has, before the left parenthesis, a <em>MethodName</em> of the form <code>super</code> . <i>Identifier</i>, then:
<ul>
<a name="289657"></a>
<li>If the method is <code>abstract</code>, a compile-time error occurs
<a name="289632"></a>
<li>If the method invocation occurs in a static context, a compile-time error occurs
</ul>
<a name="289639"></a>
<li>If the method invocation has, before the left parenthesis, a <em>MethodName</em> of the form <i>ClassName</i>.<code>super</code> . <i>Identifier</i>, then:
<ul>
<a name="289662"></a>
<li>If the method is <code>abstract</code>, a compile-time error occurs
<a name="289663"></a>
<li>If the method invocation occurs in a static context, a compile-time error occurs
<a name="289672"></a>
<li>Otherwise, let <i>C</i> be the class denoted by <i>ClassName</i>. If the invocation is not directly enclosed by <i>C</i> or an inner class of <i>C</i>, then a compile-time error occurs
</ul>
<a name="289640"></a>
<li>If the compile-time declaration for the method invocation is <code>void</code>, then the method invocation must be a top-level expression, that is, the <em>Expression</em> in an expression statement <a href="statements.doc.html#5984">(&#167;14.8)</a> or in the <em>ForInit</em> or <em>ForUpdate</em> part of a <code>for</code> statement <a href="statements.doc.html#24588">(&#167;14.13)</a>, or a compile-time error occurs. (The reason is that such a method invocation produces no value and so must be used only in a situation where a value is not needed.)
</ul><a name="38703"></a>
The following compile-time information is then associated with the method invocation for use at run time:<p>
<ul><a name="38709"></a>
<li>The name of the method.
<a name="250715"></a>
<li>The qualifying type of the method invocation <a href="binaryComp.doc.html#44909">(&#167;13.1)</a>.
<a name="38716"></a>
<li>The number of parameters and the types of the parameters, in order.
<a name="38717"></a>
<li>The result type, or <code>void</code>, as declared in the compile-time declaration.
<a name="38712"></a>
<li>The invocation mode, computed as follows:
<ul>
<a name="38723"></a>
<li>If the compile-time declaration has the <code>static</code> modifier, then the invocation mode is <code>static</code>.
<a name="43892"></a>
<li>Otherwise, if the compile-time declaration has the <code>private</code> modifier, then the invocation mode is <code>nonvirtual</code>.
<a name="262784"></a>
<li>Otherwise, if the part of the method invocation before the left parenthesis is of the form <code>super</code> <code>.</code> <em>Identifier</em> or of the form ClassName.super.Identifier<em> </em>then the invocation mode is <code>super</code>.
<a name="38796"></a>
<li>Otherwise, if the compile-time declaration is in an interface, then the invocation mode is <code>interface</code>.
<a name="38732"></a>
<li>Otherwise, the invocation mode is <code>virtual</code>.
</ul>
</ul><a name="38220"></a>
If the compile-time declaration for the method invocation is not <code>void</code>, then the type of the method invocation expression is the result type specified in the compile-time declaration.<p>
<a name="45677"></a>
<h3>15.12.4    Runtime Evaluation of Method Invocation</h3>
<a name="45678"></a>
At run time, method invocation requires five steps. First, a <em>target reference</em> 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.<p>
<a name="38359"></a>
<h4>15.12.4.1    Compute Target Reference (If Necessary)</h4>
<a name="38338"></a>
There are several cases to consider, depending on which of the four productions for <em>MethodInvocation</em> <a href="expressions.doc.html#20448">(&#167;15.12)</a> is involved:<p>
<ul><a name="239420"></a>
<li>If the first production for <em>MethodInvocation</em>, which includes a <em>MethodName</em>, is involved, then there are three subcases:
<ul>
<a name="239421"></a>
<li>If the <em>MethodName</em> is a simple name, that is, just an <em>Identifier</em>, then there are two subcases:
<ul>
<a name="38362"></a>
<li>If the invocation mode is <code>static</code>, then there is no target reference.
<a name="267467"></a>
<li>Otherwise, let <i>T</i> be the enclosing type declaration of which the method is a member, and let <em>n</em> be an integer such that <i>T</i> is the <em>n</em>th lexically enclosing type declaration <a href="classes.doc.html#262890">(&#167;8.1.2)</a> of the class whose declaration immediately contains the method invocation. Then the target reference is the <em>n</em>th lexically enclosing instance <a href="classes.doc.html#262890">(&#167;8.1.2)</a> of <code>this</code>. It is a compile-time error if the <em>n</em>th lexically enclosing instance <a href="classes.doc.html#262890">(&#167;8.1.2)</a> of <code>this</code> does not exist.
</ul>
<a name="38341"></a>
<li>If the <em>MethodName</em> is a qualified name of the form <em>TypeName</em> <code>.</code> <em>Identifier</em>, then there is no target reference.
<a name="38805"></a>
<li>If the <em>MethodName</em> is a qualified name of the form <em>FieldName</em> <code>.</code> <em>Identifier</em>, then there are two subcases:
<ul>
<a name="38806"></a>
<li>If the invocation mode is <code>static</code>, then there is no target reference.
<a name="38807"></a>
<li>Otherwise, the target reference is the value of the expression <em>FieldName</em>.
</ul>
</ul>
<a name="38815"></a>
<li>If the second production for <em>MethodInvocation</em>, which includes a <em>Primary</em>, is involved, then there are two subcases:
<ul>
<a name="38816"></a>
<li>If the invocation mode is <code>static</code>, then there is no target reference. The expression <em>Primary </em>is evaluated, but the result is then discarded.
<a name="38817"></a>
<li>Otherwise, the expression <em>Primary </em>is evaluated and the result is used as the target reference.
</ul>
</ul><ul><a name="38346"></a>
In either case, if the evaluation of the <em>Primary</em> expression completes abruptly, then no part of any argument expression appears to have been evaluated, and the method invocation completes abruptly for the same reason.
</ul><ul><a name="38347"></a>
<li>If the third production for <em>MethodInvocation</em>, which includes the keyword <code>super</code>, is involved, then the target reference is the value of <code>this</code>.
<a name="251575"></a>
<li>If the fourth production for MethodInvocation, <em>ClassName</em>.super, is involved, then the target reference is the value of <em>ClassName</em>.this.
</ul><a name="45449"></a>
<h4>15.12.4.2    Evaluate Arguments</h4>
<a name="21593"></a>
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.<p>
<a name="45453"></a>
<h4>15.12.4.3    Check Accessibility of Type and Method</h4>
<a name="251693"></a>
Let <i>C</i> be the class containing the method invocation, and let <i>T</i> be the qualifying type of the method invocation <a href="binaryComp.doc.html#44909">(&#167;13.1)</a>, and <i>m</i> be the name of the method, as determined at compile time <a href="expressions.doc.html#23617">(&#167;15.12.3)</a>. An implementation of the Java programming language must insure, as part of linkage, that the method <i>m</i> still exists in the type <i>T</i>. If this is not true, then a <code>NoSuchMethodError</code> (which is a subclass of <code>IncompatibleClassChangeError</code>) occurs. If the invocation mode is <code>interface</code>, 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 <code>IncompatibleClassChangeError</code> occurs.<p>
<a name="251696"></a>
The implementation must also insure, during linkage, that the type <i>T</i> and the method <i>m</i> are accessible. For the type <i>T</i>:<p>
<ul><a name="45547"></a>
<li>If <i>T</i> is in the same package as <i>C</i>, then <i>T</i> is accessible.
<a name="45548"></a>
<li>If <i>T</i> is in a different package than <i>C</i>, and <i>T</i> is <code>public</code>, then <i>T</i> is accessible.
<a name="253445"></a>
<li>If <i>T</i> is in a different package than <i>C</i>, and <i>T</i> is protected, then <i>T</i> is accessible if and only if <i>C</i> is a subclass of <i>T</i>.
</ul><a name="239521"></a>
For the method <i>m</i>:<p>
<ul><a name="45542"></a>
<li>If <i>m</i> is <code>public</code>, then <i>m</i> is accessible. (All members of interfaces are <code>public</code> <a href="interfaces.doc.html#32392">(&#167;9.2)</a>).
<a name="45694"></a>
<li>If <i>m</i> is <code>protected</code>, then <i>m</i> is accessible if and only if either <i>T</i> is in the same package as <i>C</i>, or <i>C</i> is <i>T</i> or a subclass of <i>T</i>.
<a name="45695"></a>
<li>If <i>m</i> has default (package) access, then <i>m</i> is accessible if and only if <i>T</i> is in the same package as <i>C</i>.
<a name="45565"></a>
<li>If <i>m</i> is <code>private</code>, then <i>m</i> is accessible if and only if  <i>C</i> is <i>T</i>, or C encloses T, or T encloses C, or T and C are both enclosed by a third class<i></i>.
</ul><a name="45566"></a>
If either <i>T</i> or <i>m</i> is not accessible, then an <code>IllegalAccessError</code> occurs <a href="execution.doc.html#44487">(&#167;12.3)</a>.<p>
<a name="45606"></a>
<h4>15.12.4.4    Locate Method to Invoke</h4>
<a name="38785"></a>
The strategy for method lookup depends on the invocation mode.<p>
<a name="45702"></a>
If the invocation mode is <code>static</code>, no target reference is needed and overriding is not allowed. Method <i>m</i> of class <i>T</i> is the one to be invoked.<p>
<a name="45395"></a>
Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is <code>null</code>, a <code>NullPointerException</code> is thrown at this point. Otherwise, the target reference is said to refer to a <em>target object</em> and will be used as the value of the keyword <code>this</code> in the invoked method. The other four possibilities for the invocation mode are then considered.<p>
<a name="38856"></a>
If the invocation mode is <code>nonvirtual</code>, overriding is not allowed. Method <i>m</i> of class <i>T</i> is the one to be invoked.<p>
<a name="38864"></a>
Otherwise, the invocation mode is <code>interface</code>, <code>virtual</code>, or <code>super</code>, and overriding may occur. A <em>dynamic method lookup</em> is used. The dynamic lookup process starts from a class <i>S</i>, determined as follows:<p>
<ul><a name="290412"></a>
<li>If the invocation mode is <code>interface</code> or <code>virtual</code>, then <i>S</i> is initially the actual run-time class <i>R</i> of the target object. This is true even if the target object is an array instance. (Note that for invocation mode <code>interface</code>, <i>R</i> necessarily implements <i>T</i>; for invocation mode <code>virtual</code>, <i>R</i> is necessarily either <i>T</i> or a subclass of <i>T</i>.)
<a name="45403"></a>
<li>If the invocation mode is <code>super</code>, then <i>S</i> is initially the qualifying type <a href="binaryComp.doc.html#44909">(&#167;13.1)</a> of the method invocation.
</ul><a name="39033"></a>
The dynamic method lookup uses the following procedure to search class <i>S</i>, and then the superclasses of class <i>S</i>, as necessary, for method <i>m</i>.<p>
<a name="250473"></a>
Let <i>X</i> be the compile-time type of the target reference of the method invocation.<p>
<ol>
<a name="250480"></a>
<li>If class <i>S</i> contains a declaration for a non-abstract method named <i>m</i> 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 <a href="expressions.doc.html#23617">(&#167;15.12.3)</a>, then:
<ul>
<a name="250485"></a>
<li>If the invocation mode is <code>super</code> or <code>interface</code>, then this is the method to be invoked, and the procedure terminates.
<a name="250487"></a>
<li>If the invocation mode is <code>virtual</code>, and the declaration in <i>S</i> overrides <a href="classes.doc.html#227927">(&#167;8.4.6.1)</a> <i>X.m</i>, then the method declared in <i>S</i> is the method to be invoked, and the procedure terminates.
</ul>
<a name="267561"></a>
<li>Otherwise, if <i>S</i> has a superclass, this same lookup procedure is performed recursively using the direct superclass of <i>S</i> in place of <i>S</i>; the method to be invoked is the result of the recursive invocation of this lookup procedure.
</ol>
<a name="264492"></a>
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 <em>The Java Virtual Machine Specification, Second Edition</em>.<p>
<a name="267569"></a>
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.<p>
<a name="39078"></a>
<h4>15.12.4.5    Create Frame, Synchronize, Transfer Control</h4>
<a name="39080"></a>
A method <i>m</i> in some class <i>S</i> has been identified as the one to be invoked.<p>
<a name="39084"></a>
Now a new <em>activation frame</em> 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 <code>OutOfMemoryError</code> is thrown.<p>
<a name="39085"></a>
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 <code>this</code>, if there is a target reference. Before each argument value is assigned to its corresponding parameter variable, it is subjected to method invocation conversion <a href="conversions.doc.html#12687">(&#167;5.3)</a>, which includes any required value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>.<p>
<a name="42183"></a>
If the method <i>m</i> is a <code>native</code> method but the necessary native, implementation-dependent binary code has not been loaded or otherwise cannot be dynamically linked, then an <code>UnsatisfiedLinkError</code> is thrown.<p>
<a name="41731"></a>
If the method <i>m</i> is not <code>synchronized</code>, control is transferred to the body of the method <i>m</i> to be invoked.<p>
<a name="264497"></a>
If the method <i>m</i> is <code>synchronized</code>, 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 <code>Class</code> object for class <i>S</i>, the class of the method <i>m</i>, must be locked. Control is then transferred to the body of the method <i>m</i> 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 <code>synchronized</code> statement <a href="statements.doc.html#255769">(&#167;14.18)</a>.<p>
<a name="39122"></a>
<h4>15.12.4.6    Example: Target Reference and Static Methods</h4>
<a name="39148"></a>
When a target reference is computed and then discarded because the invocation mode is <code>static</code>, the reference is not examined to see whether it is <code>null</code>:<p>
<blockquote><pre>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();
       }
}
</pre></blockquote><a name="39138"></a>
which prints:<p>
<blockquote><pre>Mount Monadnock
</pre></blockquote><a name="39140"></a>
Here <code>favorite</code> returns <code>null</code>, yet no <code>NullPointerException</code> is thrown.<p>
<a name="23837"></a>
<h4>15.12.4.7    Example: Evaluation Order</h4>
<a name="23841"></a>
As part of an instance method invocation <a href="expressions.doc.html#20448">(&#167;15.12)</a>, 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.<p>
<a name="23842"></a>
So, for example, in:<p>
<blockquote><pre>class Test {
       public static void main(String[] args) {
               String s = "one";
               if (s.startsWith(s = "two"))
                       System.out.println("oops");
       }
}
</pre></blockquote><a name="272804"></a>
the occurrence of <code>s</code> before "<code>.startsWith</code>" is evaluated first, before the argument expression <code>s="two"</code>. Therefore, a reference to the string <code>"one"</code> is remembered as the target reference before the local variable s is changed to refer to the string <code>"two"</code>. As a result, the <code>startsWith</code> method is invoked for target object <code>"one"</code> with argument <code>"two"</code>, so the result of the invocation is <code>false</code>, as the string <code>"one"</code> does not start with <code>"two"</code>. It follows that the test program does not print "<code>oops</code>".<p>
<a name="239650"></a>
<h4>15.12.4.8    Example: Overriding</h4>
<a name="239651"></a>
In the example:<p>
<blockquote><pre>class Point {
       final int EDGE = 20;
       int x, y;
       void move(int dx, int dy) {
               x += dx; y += dy;
               if (Math.abs(x) &gt;= EDGE || Math.abs(y) &gt;= 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;
       }
}
</pre></blockquote><a name="239673"></a>
the subclass <code>ColoredPoint</code> extends the <code>clear</code> abstraction defined by its superclass <code>Point</code>. It does so by overriding the <code>clear</code> method with its own method, which invokes the <code>clear</code> method of its superclass, using the form <code>super.clear</code>.<p>
<a name="239674"></a>
This method is then invoked whenever the target object for an invocation of <code>clear</code> is a <code>ColoredPoint</code>. Even the method <code>move</code> in <code>Point</code> invokes the <code>clear</code> method of class <code>ColoredPoint</code> when the class of <code>this</code> is <code>ColoredPoint</code>, as shown by the output of this test program:<p>
<blockquote><pre>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);
       }
}
</pre></blockquote><a name="239688"></a>
which is:<p>
<blockquote><pre>p.move(20,20):
       Point clear
cp.move(20,20):
       ColoredPoint clear
       Point clear
p.move(20,20), p colored:
       ColoredPoint clear
       Point clear
</pre></blockquote>
<a name="239749"></a>
Overriding is sometimes called "late-bound self-reference"; in this example it means that the reference to <code>clear</code> in the body of <code>Point.move</code> (which is really syntactic shorthand for <code>this.clear</code>) invokes a method chosen "late" (at run time, based on the run-time class of the object referenced by <code>this</code>) rather than a method chosen "early" (at compile time, based only on the type of <code>this</code>). This provides the programmer a powerful way of extending abstractions and is a key idea in object-oriented programming.<p>
<a name="239751"></a>
<h4>15.12.4.9    Example: Method Invocation using super</h4>
<a name="239647"></a>
An overridden instance method of a superclass may be accessed by using the keyword <code>super</code> to access the members of the immediate superclass, bypassing any overriding declaration in the class that contains the method invocation.<p>
<a name="39225"></a>
When accessing an instance variable, <code>super</code> means the same as a cast of <code>this</code> <a href="expressions.doc.html#20860">(&#167;15.11.2)</a>, but this equivalence does not hold true for method invocation. This is demonstrated by the example:<p>
<blockquote><pre>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();
       }
}
</pre></blockquote><a name="42586"></a>
which produces the output:<p>
<blockquote><pre>s()=                                   3
super.s()=                                      2
((T2)this).s()=                                 3
((T1)this).s()=                                 3
</pre></blockquote>
<a name="264502"></a>
The casts to types <code>T1</code> and <code>T2</code> 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 <code>this</code>. A cast does not change the class of an object; it only checks that the class is compatible with the specified type.<p>
<a name="239587"></a>
<h2>15.13    Array Access Expressions</h2>
<a name="39327"></a>
An array access expression refers to a variable that is a component of an array.<p>
<ul><pre>
<em>ArrayAccess:
       ExpressionName </em>[<em> Expression </em>]<em>
       PrimaryNoNewArray</em> [<em> Expression</em> ]
</pre></ul><a name="19392"></a>
An array access expression contains two subexpressions, the <em>array reference expression</em> (before the left bracket) and the <em>index expression</em> (within the brackets). Note that the array reference expression may be a name or any primary expression that is not an array creation expression <a href="expressions.doc.html#46168">(&#167;15.10)</a>.<p>
<a name="22123"></a>
The type of the array reference expression must be an array type (call it <i>T</i><code>[]</code>, an array whose components are of type <i>T</i>) or a compile-time error results. Then the type of the array access expression is <i>T</i>.<p>
<a name="22103"></a>
The index expression undergoes unary numeric promotion <a href="conversions.doc.html#170952">(&#167;5.6.1)</a>; the promoted type must be <code>int</code>.<p>
<a name="23960"></a>
The result of an array reference is a variable of type <i>T</i>, 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 <code>final</code>, even if the array reference was obtained from a <code>final</code> variable.<p>
<a name="23958"></a>
<h3>15.13.1    Runtime Evaluation of Array Access</h3>
<a name="39346"></a>
An array access expression is evaluated using the following procedure:<p>
<ul><a name="22142"></a>
<li>First, the array reference expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason and the index expression is not evaluated.
<a name="22130"></a>
<li>Otherwise, the index expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason.
<a name="22098"></a>
<li>Otherwise, if the value of the array reference expression is <code>null</code>, then a <code>NullPointerException</code> &#32;is thrown.
<a name="6936"></a>
<li>Otherwise, the value of the array reference expression indeed refers to an array. If the value of the index expression is less than zero, or greater than or equal to the array's length, then an <code>ArrayIndexOutOfBoundsException</code> is thrown.
<a name="264507"></a>
<li>Otherwise, the result of the array access is the variable of type T, within the array, selected by the value of the index expression. (Note that this resulting variable, which is a component of the array, is never considered <code>final</code>, even if the array reference expression is a <code>final</code> variable.)
</ul><a name="23902"></a>
<h3>15.13.2    Examples: Array Access Evaluation Order</h3>
<a name="23906"></a>
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 <code>a[(a=b)[3]]</code>, the expression <code>a</code> is fully evaluated before the expression <code>(a=b)[3]</code>; this means that the original value of <code>a</code> is fetched and remembered while the expression <code>(a=b)[3]</code> is evaluated. This array referenced by the original value of <code>a</code> is then subscripted by a value that is element <code>3</code> of another array (possibly the same array) that was referenced by <code>b</code> and is now also referenced by <code>a</code>.<p>
<a name="23907"></a>
Thus, the example:<p>
<blockquote><pre>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]]);
       }
}
</pre></blockquote><a name="23915"></a>
prints:<p>
<blockquote><pre>14
</pre></blockquote><a name="290083"></a>
because the monstrous expression's value is equivalent to <code>a[b[3]]</code> or <code>a[3]</code> or <code>14</code>.<p>
<a name="290084"></a>
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:<p>
<blockquote><pre>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");
       }
}
</pre></blockquote><a name="23931"></a>
prints: <p>
<blockquote><pre>java.lang.Exception: Ciao, index=1
</pre></blockquote><a name="23933"></a>
because the embedded assignment of <code>2</code> to <code>index</code> never occurs.<p>
<a name="23937"></a>
If the array reference expression produces <code>null</code> instead of a reference to an array, then a <code>NullPointerException</code> 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:<p>
<blockquote><pre>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; }
}
</pre></blockquote><a name="23950"></a>
prints:<p>
<blockquote><pre>java.lang.NullPointerException, index=2
</pre></blockquote><a name="23952"></a>
because the embedded assignment of <code>2</code> to <code>index</code> occurs before the check for a null pointer. As a related example, the program:<p>
<blockquote><pre>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!");
       }
}
</pre></blockquote><a name="36149"></a>
always prints:<p>
<blockquote><pre>java.lang.Exception: Twenty-three skidoo!
</pre></blockquote>
<a name="264512"></a>
A <code>NullPointerException</code> 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 <code>null</code>.<p>
<a name="36254"></a>
<h2>15.14    Postfix Expressions</h2>
<a name="39432"></a>
Postfix expressions include uses of the postfix <code>++</code> and <code>--</code> operators. Also, as discussed in <a href="expressions.doc.html#23302">&#167;15.8</a>, 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.<p>
<ul><pre>
<em>PostfixExpression:
       Primary
       ExpressionName
       PostIncrementExpression
       PostDecrementExpression<strong>
</strong></em></pre></ul><a name="39438"></a>
<h3>15.14.1    Postfix Increment Operator ++</h3>
<ul><pre>
<em>PostIncrementExpression:
       PostfixExpression </em>++
</pre></ul><a name="40093"></a>
A postfix expression followed by a <code>++</code> 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.<p>
<a name="249305"></a>
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 <code>1</code> is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion <a href="conversions.doc.html#25363">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable <em>before </em>the new value is stored.<p>
<a name="249315"></a>
Note that the binary numeric promotion mentioned above may include value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>. If necessary, value set conversion is applied to the sum prior to its being stored in the variable.<p>
<a name="249312"></a>
A variable that is declared <code>final</code> cannot be incremented, because when an access of a <code>final</code> 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.<p>
<a name="4987"></a>
<h3>15.14.2    Postfix Decrement Operator --</h3>
<ul><pre>
<em>PostDecrementExpression:
       PostfixExpression </em>--
</pre></ul><a name="40094"></a>
A postfix expression followed by a <code>--</code> 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.<p>
<a name="39668"></a>
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 <code>1</code> is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion <a href="conversions.doc.html#25363">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable <em>before </em>the new value is stored.<p>
<a name="249327"></a>
Note that the binary numeric promotion mentioned above may include value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>. If necessary, value set conversion is applied to the difference prior to its being stored in the variable.<p>
<a name="41352"></a>
A variable that is declared <code>final</code> cannot be decremented, because when an access of a <code>final</code> 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.<p>
<a name="4990"></a>
<h2>15.15    Unary Operators</h2>
<a name="31520"></a>
The <em>unary operators</em> include <code>+</code>, <code>-</code>, <code>++</code>, <code>--</code>, <code>~</code>, <code>!</code>, and cast operators. Expressions with unary operators group right-to-left, so that <code>-~x</code> means the same as <code>-(~x)</code>.<p>
<ul><pre>
<em>UnaryExpression:
       PreIncrementExpression
       PreDecrementExpression
</em>   +<em> UnaryExpression
       </em>-<em> UnaryExpression
       UnaryExpressionNotPlusMinus

PreIncrementExpression:
       </em>++<em> UnaryExpression

PreDecrementExpression:
       </em>--<em> UnaryExpression

UnaryExpressionNotPlusMinus:
       PostfixExpression
       </em>~<em> UnaryExpression
       </em>!<em> UnaryExpression
       CastExpression
</em></pre></ul><a name="29719"></a>
The following productions from <a href="expressions.doc.html#238146">&#167;15.16</a> are repeated here for convenience:<p>
<ul><pre>
<em>CastExpression:
       </em>(<em> PrimitiveType </em>)<em> UnaryExpression
       </em>(<em> ReferenceType </em>)&#32;U<em>naryExpressionNotPlusMinus</em>
</pre></ul><a name="39547"></a>
<h3>15.15.1    Prefix Increment Operator ++</h3>
<a name="5002"></a>
A unary expression preceded by a <code>++</code> 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.<p>
<a name="39621"></a>
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 <code>1</code> is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion <a href="conversions.doc.html#25363">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable <em>after </em>the new value is stored.<p>
<a name="249342"></a>
Note that the binary numeric promotion mentioned above may include value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>. If necessary, value set conversion is applied to the sum prior to its being stored in the variable.<p>
<a name="239134"></a>
A variable that is declared <code>final</code> cannot be incremented, because when an access of a <code>final</code> 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.<p>
<a name="239136"></a>
<h3>15.15.2    Prefix Decrement Operator --</h3>
<a name="5005"></a>
A unary expression preceded by a <code>--</code> 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.<p>
<a name="39634"></a>
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 <code>1</code> is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion <a href="conversions.doc.html#25363">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable <em>after </em>the new value is stored.<p>
<a name="249349"></a>
Note that the binary numeric promotion mentioned above may include value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>. If necessary, format conversion is applied to the difference prior to its being stored in the variable.<p>
<a name="41323"></a>
A variable that is declared <code>final</code> cannot be decremented, because when an access of a <code>final</code> 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.<p>
<a name="24924"></a>
<h3>15.15.3    Unary Plus Operator +</h3>
<a name="24926"></a>
The type of the operand expression of the unary <code>+</code> operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion <a href="conversions.doc.html#170952">(&#167;5.6.1)</a> 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.<p>
<a name="39701"></a>
At run time, the value of the unary plus expression is the promoted value of the operand.<p>
<a name="236345"></a>
<h3>15.15.4    Unary Minus Operator -</h3>
<a name="39711"></a>
The type of the operand expression of the unary <code>-</code> operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion <a href="conversions.doc.html#170952">(&#167;5.6.1)</a> is performed on the operand. The type of the unary minus expression is the promoted type of the operand.<p>
<a name="251073"></a>
Note that unary numeric promotion performs value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>. 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.<p>
<a name="249384"></a>
At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.<p>
<a name="79921"></a>
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 <code>int</code> or <code>long</code> results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values <code>x</code>, <code>-x</code> equals <code>(~x)+1</code>.<p>
<a name="5013"></a>
For floating-point values, negation is not the same as subtraction from zero, because if <code>x</code> is <code>+0.0</code>, then <code>0.0-x</code> is <code>+0.0</code>, but <code>-x</code> is <code>-0.0</code>. Unary minus merely inverts the sign of a floating-point number. Special cases of interest:<p>
<ul><a name="5014"></a>
<li>If the operand is NaN, the result is NaN (recall that NaN has no sign).
<a name="5015"></a>
<li>If the operand is an infinity, the result is the infinity of opposite sign.
<a name="5016"></a>
<li>If the operand is a zero, the result is the zero of opposite sign.
</ul><a name="5017"></a>
<h3>15.15.5    Bitwise Complement Operator ~</h3>
<a name="39739"></a>
The type of the operand expression of the unary <code>~</code> operator must be a primitive integral type, or a compile-time error occurs. Unary numeric promotion <a href="conversions.doc.html#170952">(&#167;5.6.1)</a> is performed on the operand. The type of the unary bitwise complement expression is the promoted type of the operand.<p>
<a name="39743"></a>
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, <code>~x</code> &#32;equals <code>(-x)-1</code>.<p>
<a name="13350"></a>
<h3>15.15.6    Logical Complement Operator !</h3>
<a name="39767"></a>
The type of the operand expression of the unary <code>!</code> operator must be <code>boolean,</code> or a compile-time error occurs. The type of the unary logical complement expression is <code>boolean</code>.<p>
<a name="39771"></a>
At run time, the value of the unary logical complement expression is <code>true</code> if the operand value is <code>false</code> and <code>false</code> if the operand value is <code>true</code>.<p>
<a name="238146"></a>
<h2>15.16    Cast Expressions</h2>
<a name="236464"></a>
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 <code>boolean</code>; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.<p>
<ul><pre>
<em>CastExpression:
       </em>(<em> PrimitiveType Dims<sub><i>opt</i></sub> </em>)<em> UnaryExpression
       </em>(<em> ReferenceType </em>)<em> UnaryExpressionNotPlusMinus
</em></pre></ul><a name="39813"></a>
See <a href="expressions.doc.html#4990">&#167;15.15</a> for a discussion of the distinction between <em>UnaryExpression</em> and <em>UnaryExpressionNotPlusMinus</em>.<p>
<a name="39826"></a>
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 <em>cast operator</em>.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.<p>
<a name="251082"></a>
A cast operator has no effect on the choice of value set <a href="typesValues.doc.html#9208">(&#167;4.2.3)</a> for a value of type <code>float</code> or type <code>double</code>. Consequently, a cast to type <code>float</code> within an expression that is not FP-strict <a href="expressions.doc.html#249198">(&#167;15.4)</a> does not necessarily cause its value to be converted to an element of the float value set, and a cast to type <code>double</code> 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.<p>
<a name="264531"></a>
At run time, the operand value is converted by casting conversion <a href="conversions.doc.html#20232">(&#167;5.5)</a> to the type specified by the cast operator.<p>
<a name="264536"></a>
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. <p>
<a name="264529"></a>
A <code>ClassCastException</code> is thrown if a cast is found at run time to be impermissible.<p>
<a name="239829"></a>
<h2>15.17    Multiplicative Operators</h2>
<a name="5029"></a>
The operators <code>*</code>, <code>/</code>, and <code>%</code> are called the <em>multiplicative operators</em>. They have the same precedence and are syntactically left-associative (they group left-to-right).<p>
<ul><pre>
<em>MultiplicativeExpression:
       UnaryExpression
       MultiplicativeExpression * UnaryExpression
       MultiplicativeExpression / UnaryExpression
       MultiplicativeExpression % UnaryExpression
</em></pre></ul><a name="39873"></a>
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 <a href="conversions.doc.html#170983">(&#167;5.6.2)</a>. The type of a multiplicative expression is the promoted type of its operands. If this promoted type is <code>int</code> or <code>long</code>, then integer arithmetic is performed; if this promoted type is <code>float</code> or <code>double</code>, then floating-point arithmetic is performed.<p>
<a name="251088"></a>
Note that binary numeric promotion performs value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>.<p>
<a name="5036"></a>
<h3>15.17.1    Multiplication Operator *</h3>
<a name="5037"></a>
The binary <code>*</code> 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.<p>
<a name="79991"></a>
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.<p>
<a name="5039"></a>
The result of a floating-point multiplication is governed by the rules of IEEE 754 arithmetic:<p>
<ul><a name="5040"></a>
<li>If either operand is NaN, the result is NaN.
<a name="5041"></a>
<li>If the result is not NaN, the sign of the result is positive if both operands have the same sign, and negative if the operands have different signs.
<a name="24701"></a>
<li>Multiplication of an infinity by a zero results in NaN.
<a name="24702"></a>
<li>Multiplication of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.
<a name="251092"></a>
<li>In the remaining cases, where neither an infinity nor NaN is involved, the exact mathematical product is computed. A floating-point value set is then chosen:
<ul>
<a name="251093"></a>
<li>If the multiplication expression is FP-strict <a href="expressions.doc.html#249198">(&#167;15.4)</a>:
<ul>
<a name="251094"></a>
<li>If the type of the multiplication expression is <code>float</code>, then the float value set must be chosen.
<a name="251095"></a>
<li>If the type of the multiplication expression is <code>double</code>, then the double value set must be chosen.
</ul>
<a name="251096"></a>
<li>If the multiplication expression is not FP-strict:
<ul>
<a name="251097"></a>
<li>If the type of the multiplication expression is <code>float</code>, then either the float value set or the float-extended-exponent value set may be chosen, at the whim of the implementation.
<a name="251098"></a>
<li>If the type of the multiplication expression is <code>double</code>, then either the double value set or the double-extended-exponent value set may be chosen, at the whim of the implementation.
</ul>
</ul>
</ul><ul><a name="251099"></a>
<br><br>Next, a value must be chosen from the chosen value set to represent the product. If the magnitude of the product is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. Otherwise, the product is rounded to the nearest value in the chosen value set using IEEE 754 round-to-nearest mode. The Java programming language requires support of gradual underflow as defined by IEEE 754 <a href="typesValues.doc.html#9249">(&#167;4.2.4)</a>.
</ul><a name="5045"></a>
Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a multiplication operator <code>*</code> never throws a run-time exception.<p>
<a name="5047"></a>
<h3>15.17.2    Division Operator /</h3>
<a name="5048"></a>
The binary <code>/</code> operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.<p>
<a name="45471"></a>
Integer division rounds toward <code>0</code>. That is, the quotient produced for operands <em>n</em> and <em>d</em> that are integers after binary numeric promotion <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> is an integer value <em>q</em> whose magnitude is as large as possible while satisfying <img src="15.doc.anc4.gif">; moreover, <em>q </em>is positive when <img src="15.doc.anc5.gif"> and <em>n</em> and <em>d</em> have the same sign, but <em>q</em> is negative when <img src="15.doc.anc6.gif"> and <em>n</em> and <em>d </em>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 <code>-1</code>, 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 <code>0</code>, then an <code>ArithmeticException</code> is thrown.<p>
<a name="45481"></a>
The result of a floating-point division is determined by the specification of IEEE arithmetic:<p>
<ul><a name="5054"></a>
<li>If either operand is NaN, the result is NaN.
<a name="5055"></a>
<li>If the result is not NaN, the sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
<a name="5056"></a>
<li>Division of an infinity by an infinity results in NaN.
<a name="5057"></a>
<li>Division of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.
<a name="5058"></a>
<li>Division of a finite value by an infinity results in a signed zero. The sign is determined by the rule stated above.
<a name="236610"></a>
<li>Division of a zero by a zero results in NaN; division of zero by any other finite value results in a signed zero. The sign is determined by the rule stated above.
<a name="236611"></a>
<li>Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.
<a name="251106"></a>
<li>In the remaining cases, where neither an infinity nor NaN is involved, the exact mathematical quotient is computed. A floating-point value set is then chosen:
<ul>
<a name="251107"></a>
<li>If the division expression is FP-strict <a href="expressions.doc.html#249198">(&#167;15.4)</a>:
<ul>
<a name="251108"></a>
<li>If the type of the division expression is <code>float</code>, then the float value set must be chosen.
<a name="251109"></a>
<li>If the type of the division expression is <code>double</code>, then the double value set must be chosen.
</ul>
<a name="251110"></a>
<li>If the division expression is not FP-strict:
<ul>
<a name="251111"></a>
<li>If the type of the division expression is <code>float</code>, then either the float value set or the float-extended-exponent value set may be chosen, at the whim of the implementation.
<a name="251112"></a>
<li>If the type of the division expression is <code>double</code>, then either the double value set or the double-extended-exponent value set may be chosen, at the whim of the implementation.
</ul>
</ul>
</ul><ul><a name="251113"></a>
Next, a value must be chosen from the chosen value set to represent the quotient. If the magnitude of the quotient is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. Otherwise, the quotient is rounded to the nearest value in the chosen value set using IEEE 754 round-to-nearest mode. The Java programming language requires support of gradual underflow as defined by IEEE 754 <a href="typesValues.doc.html#9249">(&#167;4.2.4)</a>.
</ul><a name="5062"></a>
Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator <code>/</code> never throws a run-time exception<p>
<a name="24956"></a>
<h3>15.17.3    Remainder Operator %</h3>
<a name="264541"></a>
The binary <code>%</code> 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.<p>
<a name="264546"></a>
In C and C++, the remainder operator accepts only integral operands, but in the Java programming language, it also accepts floating-point operands.<p>
<a name="264551"></a>
The remainder operation for operands that are integers after binary numeric promotion <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> produces a result value such that <code>(a/b)*b+(a%b)</code> is equal to <code>a</code>. 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 <code>-1</code> (the remainder is <code>0</code>). 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 <code>0</code>, then an <code>ArithmeticException</code> is thrown.Examples:<p>
<blockquote><pre>
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)
</pre></blockquote><a name="249585"></a>
The result of a floating-point remainder operation as computed by the <code>%</code> operator is <em>not</em> 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 <em>not</em> analogous to that of the usual integer remainder operator. Instead, the Java programming language defines <code>%</code> 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 <code>fmod</code>. The IEEE 754 remainder operation may be computed by the library routine <code>Math.IEEEremainder</code>.<p>
<a name="5068"></a>
The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:<p>
<ul><a name="5069"></a>
<li>If either operand is NaN, the result is NaN.
<a name="5070"></a>
<li>If the result is not NaN, the sign of the result equals the sign of the dividend.
<a name="5071"></a>
<li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
<a name="5072"></a>
<li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.
<a name="5073"></a>
<li>If the dividend is a zero and the divisor is finite, the result equals the dividend.
<a name="5074"></a>
<li>In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder <em>r</em> from the division of a dividend <em>n</em> by a divisor <em>d</em> is defined by the mathematical relation <img src="15.doc.anc.gif"> where <em>q</em> is an integer that is negative only if <img src="15.doc.anc1.gif"> is negative and positive only if <img src="15.doc.anc2.gif"> is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of <em>n</em> and <em>d</em>.
</ul><a name="264565"></a>
Evaluation of a floating-point remainder operator <code>%</code> never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur.<p>
<a name="40146"></a>
Examples:<p>
<blockquote><pre>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
</pre></blockquote><a name="15746"></a>
<h2>15.18    Additive Operators</h2>
<a name="15749"></a>
The operators <code>+</code> and <code>-</code> are called the <em>additive operators</em>. They have the same precedence and are syntactically left-associative (they group left-to-right).<p>
<ul><pre>
<em>AdditiveExpression:
       MultiplicativeExpression
       AdditiveExpression </em>+<em> MultiplicativeExpression
       AdditiveExpression </em>-<em> MultiplicativeExpression
</em></pre></ul><a name="39987"></a>
If the type of either operand of a + operator is <code>String</code>, then the operation is string concatenation.<p>
<a name="39998"></a>
Otherwise, the type of each of the operands of the <code>+</code> operator must be a primitive numeric type, or a compile-time error occurs. <p>
<a name="40002"></a>
In every case, the type of each of the operands of the binary <code>-</code> operator must be a primitive numeric type, or a compile-time error occurs. <p>
<a name="39990"></a>
<h3>15.18.1    String Concatenation Operator +</h3>
<a name="7894"></a>
If only one operand expression is of type <code>String</code>, 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 <code>String</code> 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.<p>
<a name="40220"></a>
<h4>15.18.1.1    String Conversion</h4>
<a name="40222"></a>
Any type may be converted to type <code>String</code> by <em>string conversion</em>.<p>
<a name="22621"></a>
A value <i>x</i> of primitive type <i>T</i> is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:<p>
<ul><a name="40316"></a>
<li>If <i>T</i> is <code>boolean</code>, then use <code>new</code> <code>Boolean(</code><i>x</i><code>)</code>.
<a name="40320"></a>
<li>If <i>T</i> is <code>char</code>, then use <code>new</code> <code>Character(</code><i>x</i><code>)</code>.
<a name="40265"></a>
<li>If <i>T</i> is <code>byte</code>, <code>short</code>, or <code>int</code>, then use <code>new</code> <code>Integer(</code><i>x</i><code>)</code>.
<a name="40272"></a>
<li>If <i>T</i> is <code>long</code>, then use <code>new</code> <code>Long(</code><i>x</i><code>)</code>.
<a name="40279"></a>
<li>If <i>T</i> is <code>float</code>, then use <code>new</code> <code>Float(</code><i>x</i><code>)</code>.
<a name="40286"></a>
<li>If <i>T</i> is <code>double</code>, then use <code>new</code> <code>Double(</code><i>x</i><code>)</code>.
</ul><a name="40362"></a>
This reference value is then converted to type <code>String</code> by string conversion.<p>
<a name="22740"></a>
Now only reference values need to be considered. If the reference is <code>null</code>, it is converted to the string "<code>null</code>" (four ASCII characters <code>n</code>, <code>u</code>, <code>l</code>, <code>l</code>). Otherwise, the conversion is performed as if by an invocation of the <code>toString</code> method of the referenced object with no arguments; but if the result of invoking the <code>toString</code> method is <code>null</code>, then the string "<code>null</code>" is used instead. <p>
<a name="290252"></a>
The <code>toString</code> method is defined by the primordial class <code>Object</code>; many classes override it, notably <code>Boolean</code>, <code>Character</code>, <code>Integer</code>, <code>Long</code>, <code>Float</code>, <code>Double,</code> and <code>String</code>.<p>
<a name="40226"></a>
<h4>15.18.1.2    Optimization of String Concatenation</h4>
<a name="40227"></a>
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate <code>String</code> object. To increase the performance of repeated string concatenation, a Java compiler may use the <code>StringBuffer</code> class or a similar technique to reduce the number of intermediate <code>String</code> objects that are created by evaluation of an expression.<p>
<a name="22668"></a>
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.<p>
<a name="40423"></a>
<h4>15.18.1.3    Examples of String Concatenation</h4>
<a name="40221"></a>
The example expression:<p>
<blockquote><pre>"The square root of 2 is " + Math.sqrt(2)
</pre></blockquote><a name="21343"></a>
produces the result:<p>
<blockquote><pre>"The square root of 2 is 1.4142135623730952"
</pre></blockquote>
<a name="21344"></a>
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:<p>
<blockquote><pre>
a + b + c
</pre></blockquote><a name="40518"></a>
is always regarded as meaning:<p>
<blockquote><pre>(a + b) + c
</pre></blockquote><a name="40520"></a>
Therefore the result of the expression:<p>
<blockquote><pre>1 + 2 + " fiddlers"
</pre></blockquote><a name="40522"></a>
is:<p>
<blockquote><pre>"3 fiddlers"
</pre></blockquote><a name="40524"></a>
but the result of:<p>
<blockquote><pre>"fiddlers " + 1 + 2
</pre></blockquote><a name="40526"></a>
is:<p>
<blockquote><pre>"fiddlers 12"
</pre></blockquote>
<a name="238156"></a>
In this jocular little example:<p>
<blockquote><pre>
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!");
       }
}
</pre></blockquote><a name="40427"></a>
the method <code>printSong</code> will print a version of a children's song. Popular values for stuff include <code>"pop"</code> and <code>"beer"</code>; the most popular value for <code>n</code> is <code>100</code>. Here is the output that results from <code>Bottles.printSong("slime", 3)</code>:<p>
<blockquote><pre>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!
</pre></blockquote>
<a name="40459"></a>
In the code, note the careful conditional generation of the singular "<code>bottle</code>" when appropriate rather than the plural "<code>bottles</code>"; note also how the string concatenation operator was used to break the long constant string:<p>
<blockquote><pre>
"You take one down and pass it around:"
</pre></blockquote>
<a name="264580"></a>
into two pieces to avoid an inconveniently long line in the source code.<p>
<a name="13510"></a>
<h3>15.18.2    Additive Operators (+ and -) for Numeric Types</h3>
<a name="235182"></a>
The binary <code>+</code> operator performs addition when applied to two operands of numeric type, producing the sum of the operands. The binary <code>-</code> operator performs subtraction, producing the difference of two numeric operands.<p>
<a name="39970"></a>
Binary numeric promotion is performed on the operands <a href="conversions.doc.html#170983">(&#167;5.6.2)</a>. The type of an additive expression on numeric operands is the promoted type of its operands. If this promoted type is <code>int</code> or <code>long</code>, then integer arithmetic is performed; if this promoted type is <code>float</code> or <code>double</code>, then floating-point arithmetic is performed.<p>
<a name="251120"></a>
Note that binary numeric promotion performs value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>.<p>
<a name="39968"></a>
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.<p>
<a name="13512"></a>
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.<p>
<a name="13513"></a>
The result of a floating-point addition is determined using the following rules of IEEE arithmetic:<p>
<ul><a name="13514"></a>
<li>If either operand is NaN, the result is NaN.
<a name="13515"></a>
<li>The sum of two infinities of opposite sign is NaN.
<a name="13516"></a>
<li>The sum of two infinities of the same sign is the infinity of that sign.
<a name="13517"></a>
<li>The sum of an infinity and a finite value is equal to the infinite operand.
<a name="13518"></a>
<li>The sum of two zeros of opposite sign is positive zero.
<a name="13519"></a>
<li>The sum of two zeros of the same sign is the zero of that sign.
<a name="13520"></a>
<li>The sum of a zero and a nonzero finite value is equal to the nonzero operand.
<a name="13521"></a>
<li>The sum of two nonzero finite values of the same magnitude and opposite sign is positive zero.
<a name="251124"></a>
<li>In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, and the operands have the same sign or have different magnitudes, the exact mathematical sum is computed. A floating-point value set is then chosen:
<ul>
<a name="251125"></a>
<li>If the addition expression is FP-strict <a href="expressions.doc.html#249198">(&#167;15.4)</a>:
<ul>
<a name="251126"></a>
<li>If the type of the addition expression is <code>float</code>, then the float value set must be chosen.
<a name="251127"></a>
<li>If the type of the addition expression is <code>double</code>, then the double value set must be chosen.
</ul>
<a name="251128"></a>
<li>If the addition expression is not FP-strict:
<ul>
<a name="251129"></a>
<li>If the type of the addition expression is <code>float</code>, then either the float value set or the float-extended-exponent value set may be chosen, at the whim of the implementation.
<a name="251130"></a>
<li>If the type of the addition expression is <code>double</code>, then either the double value set or the double-extended-exponent value set may be chosen, at the whim of the implementation.
</ul>
</ul>
</ul><ul><a name="251131"></a>
Next, a value must be chosen from the chosen value set to represent the sum. If the magnitude of the sum is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. Otherwise, the sum is rounded to the nearest value in the chosen value set using IEEE 754 round-to-nearest mode. The Java programming language requires support of gradual underflow as defined by IEEE 754 <a href="typesValues.doc.html#9249">(&#167;4.2.4)</a>.
</ul><a name="13523"></a>
The binary <code>-</code> 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 <code>a-b</code> produces the same result as <code>a+(-b)</code>. <p>
<a name="290253"></a>
Note that, for integer values, subtraction from zero is the same as negation. However, for floating-point operands, subtraction from zero is <em>not</em> the same as negation, because if <code>x</code> is <code>+0.0</code>, then <code>0.0-x</code> is <code>+0.0</code>, but <code>-x</code> is <code>-0.0</code>. <p>
<a name="13524"></a>
Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a run-time exception.<p>
<a name="5121"></a>
<h2>15.19    Shift Operators</h2>
<a name="5122"></a>
The <em>shift operators</em> include left shift <code>&lt;&lt;</code>, signed right shift <code>&gt;&gt;</code>, and unsigned right shift <code>&gt;&gt;&gt;</code>; 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.<p>
<ul><pre>
<em>ShiftExpression:
       AdditiveExpression
       ShiftExpression &lt;&lt; AdditiveExpression
       ShiftExpression &gt;&gt; AdditiveExpression
       ShiftExpression &gt;&gt;&gt; AdditiveExpression
</em></pre></ul><a name="40554"></a>
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 <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> is <em>not</em> performed on the operands; rather, unary numeric promotion <a href="conversions.doc.html#170952">(&#167;5.6.1)</a> is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.<p>
<a name="13680"></a>
If the promoted type of the left-hand operand is <code>int</code>, 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 <code>&amp;</code> <a href="expressions.doc.html#5233">(&#167;15.22.1)</a> with the mask value <code>0x1f</code>. The shift distance actually used is therefore always in the range 0 to 31, inclusive.<p>
<a name="19183"></a>
If the promoted type of the left-hand operand is <code>long</code>, 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 <code>&amp;</code> <a href="expressions.doc.html#5233">(&#167;15.22.1)</a> with the mask value <code>0x3f</code>. The shift distance actually used is therefore always in the range 0 to 63, inclusive.<p>
<a name="19187"></a>
At run time, shift operations are performed on the two's complement integer representation of the value of the left operand.<p>
<a name="19188"></a>
The value of <code>n&lt;&lt;s</code> is <code>n</code> left-shifted <code>s</code> bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power <code>s</code>.<p>
<a name="5140"></a>
The value of <code>n&gt;&gt;s</code> is <code>n</code> right-shifted <code>s</code> bit positions with sign-extension. The resulting value is <img src="15.doc.anc3.gif">. For nonnegative values of <code>n</code>, this is equivalent to truncating integer division, as computed by the integer division operator <code>/</code>, by two to the power <code>s</code>.<p>
<a name="40638"></a>
The value of <code>n&gt;&gt;&gt;s</code> is <code>n</code> right-shifted <code>s</code> bit positions with zero-extension. If <code>n</code> is positive, then the result is the same as that of <code>n&gt;&gt;s</code>; if <code>n</code> is negative, the result is equal to that of the expression <code>(n&gt;&gt;s)+(2&lt;&lt;~s)</code> if the type of the left-hand operand is <code>int</code>, and to the result of the expression <code>(n&gt;&gt;s)+(2L&lt;&lt;~s)</code> if the type of the left-hand operand is <code>long</code>. The added term <code>(2&lt;&lt;~s)</code> or <code>(2L&lt;&lt;~s)</code> cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, <code>~s</code> as a shift distance is equivalent to <code>31-s</code> when shifting an <code>int</code> value and to <code>63-s</code> when shifting a <code>long</code> value.)<p>
<a name="40641"></a>
<h2>15.20    Relational Operators</h2>
<a name="139595"></a>
The <em>relational operators</em> are syntactically left-associative (they group left-to-right), but this fact is not useful; for example, <code>a&lt;b&lt;c</code> parses as <code>(a&lt;b)&lt;c</code>, which is always a compile-time error, because the type of <code>a&lt;b</code> is always <code>boolean</code> and <code>&lt;</code> is not an operator on <code>boolean</code> values.<p>
<ul><pre>
<em>RelationalExpression:
       ShiftExpression
       RelationalExpression &lt; ShiftExpression
       RelationalExpression &gt; ShiftExpression
       RelationalExpression &lt;= ShiftExpression
       RelationalExpression &gt;= ShiftExpression
       RelationalExpression instanceof ReferenceType
</em></pre></ul><a name="235261"></a>
The type of a relational expression is always <code>boolean</code>.<p>
<a name="153654"></a>
<h3>15.20.1    Numerical Comparison Operators &lt;, &lt;=, &gt;, and &gt;= </h3>
<a name="40647"></a>
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 <a href="conversions.doc.html#170983">(&#167;5.6.2)</a>. If the promoted type of the operands is <code>int</code> or <code>long</code>, then signed integer comparison is performed; if this promoted type is <code>float</code> or <code>double</code>, then floating-point comparison is performed.<p>
<a name="251144"></a>
Note that binary numeric promotion performs value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>. Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.<p>
<a name="5155"></a>
The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:<p>
<ul><a name="5156"></a>
<li>If either operand is NaN, then the result is <code>false</code>.
<a name="5157"></a>
<li>All values other than NaN are ordered, with negative infinity less than all finite values, and positive infinity greater than all finite values.
<a name="5158"></a>
<li>Positive zero and negative zero are considered equal. Therefore, <code>-0.0&lt;0.0</code> is <code>false</code>, for example, but <code>-0.0&lt;=0.0</code> is <code>true</code>. (Note, however, that the methods <code>Math.min</code> and <code>Math.max</code> treat negative zero as being strictly smaller than positive zero.)
</ul><a name="5159"></a>
Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:<p>
<ul><a name="5160"></a>
<li>The value produced by the <code>&lt;</code> operator is <code>true</code> if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is <code>false</code>.
<a name="5161"></a>
<li>The value produced by the <code>&lt;=</code> operator is <code>true</code> if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is <code>false</code>.
<a name="5162"></a>
<li>The value produced by the <code>&gt;</code> operator is <code>true</code> if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is <code>false</code>.
<a name="5163"></a>
<li>The value produced by the <code>&gt;=</code> operator is <code>true</code> if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is <code>false</code>.
</ul><a name="80289"></a>
<h3>15.20.2    Type Comparison Operator instanceof</h3>
<a name="80291"></a>
The type of a <em>RelationalExpression</em> operand of the <code>instanceof</code> operator must be a reference type or the null type; otherwise, a compile-time error occurs. The <em>ReferenceType</em> mentioned after the <code>instanceof</code> operator must denote a reference type; otherwise, a compile-time error occurs.<p>
<a name="240816"></a>
At run time, the result of the <code>instanceof</code> operator is <code>true</code> if the value of the <em>RelationalExpression</em> is not <code>null</code> and the reference could be cast <a href="expressions.doc.html#238146">(&#167;15.16)</a> to the <em>ReferenceType</em> without raising a <code>ClassCastException</code>. Otherwise the result is <code>false</code>.<p>
<a name="264585"></a>
If a cast of the <em>RelationalExpression</em> to the <em>ReferenceType</em> would be rejected as a compile-time error, then the <code>instanceof</code> relational expression likewise produces a compile-time error. In such a situation, the result of the <code>instanceof</code> expression could never be <code>true</code>.<p>
<a name="238166"></a>
Consider the example program:<p>
<blockquote><pre>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
               }
       }
}
</pre></blockquote><a name="22819"></a>
This example results in two compile-time errors. The cast <code>(Point)e</code> is incorrect because no instance of <code>Element</code> or any of its possible subclasses (none are shown here) could possibly be an instance of any subclass of <code>Point</code>. The <code>instanceof</code> expression is incorrect for exactly the same reason. If, on the other hand, the class <code>Point</code> were a subclass of <code>Element</code> (an admittedly strange notion in this example):<p>
<blockquote><pre>class Point extends Element { int x, y; }
</pre></blockquote><a name="264590"></a>
then the cast would be possible, though it would require a run-time check, and the <code>instanceof</code> expression would then be sensible and valid. The cast <code>(Point)e</code> would never raise an exception because it would not be executed if the value of <code>e</code> could not correctly be cast to type <code>Point</code>.<p>
<a name="5192"></a>
<h2>15.21    Equality Operators</h2>
<a name="24723"></a>
The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, <code>a==b==c</code> parses as <code>(a==b)==c</code>. The result type of <code>a==b</code> is always <code>boolean</code>, and <code>c</code> must therefore be of type <code>boolean</code> or a compile-time error occurs. Thus, <code>a==b==c</code> does <em>not</em> test to see whether <code>a</code>, <code>b</code>, and <code>c</code> are all equal.<p>
<ul><pre>
<em>EqualityExpression:
       RelationalExpression
       EqualityExpression == RelationalExpression
       EqualityExpression != RelationalExpression
</em></pre></ul><a name="5195"></a>
The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, <code>a&lt;b==c&lt;d</code> is <code>true</code> whenever <code>a&lt;b</code> and <code>c&lt;d</code> have the same truth value.<p>
<a name="5196"></a>
The equality operators may be used to compare two operands of numeric type, or two operands of type <code>boolean</code>, 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 <code>boolean</code>.<p>
<a name="235280"></a>
In all cases, <code>a!=b</code> produces the same result as <code>!(a==b)</code>. The equality operators are commutative if the operand expressions have no side effects.<p>
<a name="5198"></a>
<h3>15.21.1    Numerical Equality Operators ==&#32;and != </h3>
<a name="40803"></a>
If the operands of an equality operator are both of primitive numeric type, binary numeric promotion is performed on the operands <a href="conversions.doc.html#170983">(&#167;5.6.2)</a>. If the promoted type of the operands is <code>int</code> or <code>long</code>, then an integer equality test is performed; if the promoted type is <code>float</code> or <code>double</code>, then a floating-point equality test is performed.<p>
<a name="251162"></a>
Note that binary numeric promotion performs value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>. Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.<p>
<a name="5203"></a>
Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:<p>
<ul><a name="5204"></a>
<li>If either operand is NaN, then the result of <code>==</code> is <code>false</code> but the result of <code>!=</code> is <code>true</code>. Indeed, the test <code>x!=x</code> is true if and only if the value of <code>x</code> is NaN. (The methods <code>Float.isNaN</code> and <code>Double.isNaN</code> may also be used to test whether a value is NaN.)
<a name="54500"></a>
<li>Positive zero and negative zero are considered equal. Therefore, <code>-0.0==0.0</code> is <code>true</code>, for example.
<a name="54501"></a>
<li>Otherwise, two distinct floating-point values are considered unequal by the equality operators. In particular, there is one value representing positive infinity and one value representing negative infinity; each compares equal only to itself, and each compares unequal to all other values.
</ul><a name="5207"></a>
Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:<p>
<ul><a name="5208"></a>
<li>The value produced by the <code>==</code> operator is <code>true</code> if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is <code>false</code>.
<a name="236629"></a>
<li>The value produced by the <code>!=</code> operator is <code>true</code> if the value of the left-hand operand is not equal to the value of the right-hand operand; otherwise, the result is <code>false</code>.
</ul><a name="54508"></a>
<h3>15.21.2    Boolean Equality Operators ==&#32;and != </h3>
<a name="80389"></a>
If the operands of an equality operator are both of type <code>boolean</code>, then the operation is boolean equality. The <code>boolean</code> equality operators are associative.<p>
<a name="5214"></a>
The result of <code>==</code> is <code>true</code> if the operands are both <code>true</code> or both <code>false</code>; otherwise, the result is <code>false</code>.<p>
<a name="5215"></a>
The result of <code>!=</code> is <code>false</code> if the operands are both <code>true</code> or both <code>false</code>; otherwise, the result is <code>true</code>. Thus <code>!=</code> behaves the same as <code>^</code> <a href="expressions.doc.html#5242">(&#167;15.22.2)</a> when applied to boolean operands.<p>
<a name="236163"></a>
<h3>15.21.3    Reference Equality Operators ==&#32;and !=</h3>
<a name="236164"></a>
If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.<p>
<a name="80399"></a>
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 <a href="conversions.doc.html#20232">(&#167;5.5)</a>. The run-time values of the two operands would necessarily be unequal.<p>
<a name="5225"></a>
At run time, the result of <code>==</code> is <code>true</code> if the operand values are both <code>null</code> or both refer to the same object or array; otherwise, the result is <code>false</code>.<p>
<a name="264595"></a>
The result of <code>!=</code> is <code>false</code> if the operand values are both <code>null</code> or both refer to the same object or array; otherwise, the result is <code>true</code>.<p>
<a name="264600"></a>
While <code>==</code> may be used to compare references of type <code>String</code>, such an equality test determines whether or not the two operands refer to the same <code>String</code> object. The result is <code>false</code> if the operands are distinct <code>String</code> objects, even if they contain the same sequence of characters. The contents of two strings <code>s</code> and <code>t</code> can be tested for equality by the method invocation <code>s.equals(t)</code>. See also <a href="lexical.doc.html#101083">&#167;3.10.5</a>.<p>
<a name="5228"></a>
<h2>15.22    Bitwise and Logical Operators</h2>
<a name="5229"></a>
The <em>bitwise</em> <em>operators</em> and <em>logical operators</em> include the AND operator <code>&amp;</code>, exclusive OR operator <code>^</code>, and inclusive OR operator <code>|</code>. These operators have different precedence, with <code>&amp;</code> having the highest precedence and <code>|</code> 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.<p>
<ul><pre>
<em>AndExpression:
       EqualityExpression
       AndExpression &amp; EqualityExpression

ExclusiveOrExpression:
       AndExpression
       ExclusiveOrExpression ^ AndExpression

InclusiveOrExpression:
       ExclusiveOrExpression
       InclusiveOrExpression | ExclusiveOrExpression
</em></pre></ul><a name="40906"></a>
The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type <code>boolean</code>. All other cases result in a compile-time error.<p>
<a name="5233"></a>
<h3>15.22.1    Integer Bitwise Operators &amp;, ^, and |</h3>
<a name="5234"></a>
When both operands of an operator <code>&amp;</code>, <code>^</code>, or <code>|</code> are of primitive integral type, binary numeric promotion is first performed on the operands <a href="conversions.doc.html#170983">(&#167;5.6.2)</a>. The type of the bitwise operator expression is the promoted type of the operands.<p>
<a name="5238"></a>
For <code>&amp;</code>, the result value is the bitwise AND of the operand values.<p>
<a name="5239"></a>
For <code>^</code>, the result value is the bitwise exclusive OR of the operand values.<p>
<a name="264605"></a>
For <code>|</code>, the result value is the bitwise inclusive OR of the operand values.<p>
<a name="264610"></a>
For example, the result of the expression <code>0xff00</code> <code>&amp;</code> <code>0xf0f0</code> is <code>0xf000</code>. The result of <code>0xff00</code> <code>^</code> <code>0xf0f0</code> is <code>0x0ff0</code>.The result of <code>0xff00</code> <code>|</code> <code>0xf0f0</code> is <code>0xfff0</code>.<p>
<a name="5242"></a>
<h3>15.22.2    Boolean Logical Operators &amp;, ^, and |</h3>
<a name="5243"></a>
When both operands of a <code>&amp;</code>, <code>^</code>, or <code>|</code> operator are of type <code>boolean</code>, then the type of the bitwise operator expression is <code>boolean</code>.<p>
<a name="5244"></a>
For <code>&amp;</code>, the result value is <code>true</code> if both operand values are <code>true</code>; otherwise, the result is <code>false</code>.<p>
<a name="5245"></a>
For <code>^</code>, the result value is <code>true</code> if the operand values are different; otherwise, the result is <code>false</code>.<p>
<a name="5246"></a>
For <code>|</code>, the result value is <code>false</code> if both operand values are <code>false</code>; otherwise, the result is <code>true</code>.<p>
<a name="5247"></a>
<h2>15.23    Conditional-And Operator &amp;&amp;</h2>
<a name="5248"></a>
The <code>&amp;&amp;</code> operator is like <code>&amp;</code> <a href="expressions.doc.html#5242">(&#167;15.22.2)</a>, but evaluates its right-hand operand only if the value of its left-hand operand is <code>true</code>. 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 <i>a</i>, <i>b</i>, and <i>c</i>, evaluation of the expression <code>((</code><i>a</i><code>)&amp;&amp;(</code><i>b</i><code>))&amp;&amp;(</code><i>c</i><code>)</code> produces the same result, with the same side effects occurring in the same order, as evaluation of the expression <code>(</code><i>a</i><code>)&amp;&amp;((</code><i>b</i><code>)&amp;&amp;(</code><i>c</i><code>))</code>.<p>
<ul><pre>
<em>ConditionalAndExpression:
       InclusiveOrExpression
       ConditionalAndExpression &amp;&amp; InclusiveOrExpression
</em></pre></ul><a name="5251"></a>
Each operand of <code>&amp;&amp;</code> must be of type <code>boolean</code>, or a compile-time error occurs. The type of a conditional-and expression is always <code>boolean</code>.<p>
<a name="41086"></a>
At run time, the left-hand operand expression is evaluated first; if its value is <code>false</code>, the value of the conditional-and expression is <code>false</code> and the right-hand operand expression is not evaluated. If the value of the left-hand operand is <code>true</code>, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus, <code>&amp;&amp;</code> computes the same result as <code>&amp;</code> on <code>boolean</code> operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.<p>
<a name="54532"></a>
<h2>15.24    Conditional-Or Operator ||</h2>
<a name="41053"></a>
The <code>||</code> operator is like <code>|</code> <a href="expressions.doc.html#5242">(&#167;15.22.2)</a>, but evaluates its right-hand operand only if the value of its left-hand operand is <code>false</code>. 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 <i>a</i>, <i>b</i>, and <i>c</i>, evaluation of the expression <code>((</code><i>a</i><code>)||(</code><i>b</i><code>))||(</code><i>c</i><code>)</code> produces the same result, with the same side effects occurring in the same order, as evaluation of the expression <code>(</code><i>a</i><code>)||((</code><i>b</i><code>)||(</code><i>c</i><code>))</code>.<p>
<ul><pre>
<em>ConditionalOrExpression:
       ConditionalAndExpression
       ConditionalOrExpression || ConditionalAndExpression
</em></pre></ul><a name="41088"></a>
Each operand of <code>||</code> must be of type <code>boolean,</code> or a compile-time error occurs. The type of a conditional-or expression is always <code>boolean</code>.<p>
<a name="264616"></a>
At run time, the left-hand operand expression is evaluated first; if its value is <code>true</code>, the value of the conditional-or expression is <code>true</code> and the right-hand operand expression is not evaluated. If the value of the left-hand operand is <code>false</code>, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression. <p>
<a name="290289"></a>
Thus, <code>||</code> computes the same result as <code>|</code> on <code>boolean</code> operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.<p>
<a name="290293"></a>
<h2>15.25    Conditional Operator ?&#32;:</h2>
<a name="5258"></a>
The conditional operator <code>?&#32;:</code> uses the boolean value of one expression to decide which of two other expressions should be evaluated.<p>
<a name="41113"></a>
The conditional operator is syntactically right-associative (it groups right-to-left), so that <code>a?b:c?d:e?f:g</code> means the same as <code>a?b:(c?d:(e?f:g))</code>.<p>
<ul><pre>
<em>ConditionalExpression:
       ConditionalOrExpression
       ConditionalOrExpression ? Expression : ConditionalExpression
</em></pre></ul><a name="236253"></a>
The conditional operator has three operand expressions; <code>?</code> appears between the first and second expressions, and <code>:</code> appears between the second and third expressions.<p>
<a name="40128"></a>
The first expression must be of type <code>boolean</code>, or a compile-time error occurs.<p>
<a name="40129"></a>
The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type <code>boolean</code>, 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.<p>
<a name="41144"></a>
Note that it is not permitted for either the second or the third operand expression to be an invocation of a <code>void</code> method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a <code>void</code> method could appear <a href="statements.doc.html#5984">(&#167;14.8)</a>.<p>
<a name="236267"></a>
The type of a conditional expression is determined as follows:<p>
<ul><a name="41198"></a>
<li>If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
<a name="236254"></a>
<li>Otherwise, if the second and third operands have numeric type, then there are several cases:
<ul>
<a name="5262"></a>
<li>If one of the operands is of type <code>byte</code> and the other is of type <code>short</code>, then the type of the conditional expression is <code>short</code>.
<a name="5264"></a>
<li>If one of the operands is of type <i>T</i> where <i>T</i> is <code>byte</code>, <code>short</code>, or <code>char</code>, and the other operand is a constant expression of type <code>int</code> whose value is representable in type <i>T</i>, then the type of the conditional expression is <i>T</i>.
<a name="249508"></a>
<li>Otherwise, binary numeric promotion <a href="conversions.doc.html#170983">(&#167;5.6.2)</a> is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a>.
</ul>
<a name="249501"></a>
<li>If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.
<a name="76547"></a>
<li>If the second and third operands are of different reference types, then it must be possible to convert one of the types to the other type (call this latter type <i>T</i>) by assignment conversion <a href="conversions.doc.html#184206">(&#167;5.2)</a>; the type of the conditional expression is <i>T</i>. It is a compile-time error if neither type is assignment compatible with the other type.
</ul><a name="40134"></a>
At run time, the first operand expression of the conditional expression is evaluated first; its <code>boolean</code> value is then used to choose either the second or the third operand expression:<p>
<ul><a name="5277"></a>
<li>If the value of the first operand is <code>true</code>, then the second operand expression is chosen.
<a name="5278"></a>
<li>If the value of the first operand is <code>false</code>, then the third operand expression is chosen.
</ul><a name="5279"></a>
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.<p>
<a name="5281"></a>
<h2>15.26    Assignment Operators</h2>
<a name="5282"></a>
There are 12 <em>assignment operators</em>; all are syntactically right-associative (they group right-to-left). Thus, <code>a=b=c</code> means <code>a=(b=c)</code>, which assigns the value of <code>c</code> to <code>b</code> and then assigns the value of <code>b</code> to <code>a</code>.<p>
<ul><pre>
<em>AssignmentExpression:
       ConditionalExpression
       Assignment

Assignment:
       LeftHandSide AssignmentOperator AssignmentExpression

LeftHandSide:
       ExpressionName
       FieldAccess
       ArrayAccess

AssignmentOperator: one of</em>
       =&#32;*=&#32;/=&#32;%=&#32;+=&#32;-=&#32;&lt;&lt;=&#32;&gt;&gt;=&#32;&gt;&gt;&gt;=&#32;&amp;=&#32;^=&#32;|=
</pre></ul><a name="236643"></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 <a href="expressions.doc.html#41267">(&#167;15.11)</a> or an array access <a href="expressions.doc.html#239587">(&#167;15.13)</a>. The type of the assignment expression is the type of the variable.<p>
<a name="41276"></a>
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.<p>
<a name="41365"></a>
A variable that is declared <code>final</code> cannot be assigned to (unless it is a blank final variable <a href="typesValues.doc.html#10931">(&#167;4.5.4)</a>), because when an access of a <code>final</code> 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.<p>
<a name="5295"></a>
<h3>15.26.1    Simple Assignment Operator =</h3>
<a name="22840"></a>
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 <a href="conversions.doc.html#184206">(&#167;5.2)</a>.<p>
<a name="41396"></a>
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:<p>
<ul><a name="238369"></a>
<li>First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
<a name="249532"></a>
<li>Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="265205"></a>
<li>Otherwise, the value of the right-hand operand is converted to the type of the left-hand variable, is subjected to value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a> to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.
</ul><a name="265215"></a>
If the left-hand operand expression is an array access expression <a href="expressions.doc.html#239587">(&#167;15.13)</a>, then many steps are required:<p>
<ul><a name="238214"></a>
<li>First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
<a name="238234"></a>
<li>Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
<a name="238236"></a>
<li>Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238216"></a>
<li>Otherwise, if the value of the array reference subexpression is <code>null</code>, then no assignment occurs and a <code>NullPointerException</code> &#32;is thrown.
<a name="238217"></a>
<li>Otherwise, the value of the array reference subexpression indeed refers to an array. If the value of the index subexpression is less than zero, or greater than &#32;or equal to the length of the array, then no assignment occurs and an <code>ArrayIndexOutOfBoundsException</code> &#32;is thrown.
<a name="238218"></a>
<li>Otherwise, the value of the index subexpression is used to select a component of the array referred to by the value of the array reference subexpression. This component is a variable; call its type <i>SC</i>. Also, let <i>TC</i> be the type of the left-hand operand of the assignment operator as determined at compile time.
<ul>
<a name="251174"></a>
<li>If <i>TC</i> is a primitive type, then <i>SC</i> is necessarily the same as <i>TC</i>. The value of the right-hand operand is converted to the type of the selected array component, is subjected to value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a> to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the array component.
<a name="238261"></a>
<li>If <i>TC</i> is a reference type, then <i>SC</i> may not be the same as <i>TC</i>, but rather a type that extends or implements <i>TC</i>. Let <i>RC</i> be the class of the object referred to by the value of the right-hand operand at run time.
<br>
The compiler may be able to prove at compile time that the array component will be of type <i>TC</i> exactly (for example, <i>TC</i> might be <code>final</code>). But if the compiler cannot prove at compile time that the array component will be of type <i>TC</i> exactly, then a check must be performed at run time to ensure that the class <i>RC</i> is assignment compatible <a href="conversions.doc.html#184206">(&#167;5.2)</a> with the actual type <i>SC</i> of the array component. This check is similar to a narrowing cast (<a href="conversions.doc.html#20232">&#167;5.5</a>, <a href="expressions.doc.html#238146">&#167;15.16</a>), except that if the check fails, an <code>ArrayStoreException</code> is thrown rather than a <code>ClassCastException</code>. Therefore:<p>
<ul>
<a name="238321"></a>
<li>If class <i>RC</i> is not assignable to type <i>SC</i>, then no assignment occurs and an <code>ArrayStoreException</code> is thrown.
</ul>
</ul></ul><a name="264626"></a>
Otherwise, the reference value of the right-hand operand is stored into the selected array component.<p>
<a name="238526"></a>
The rules for assignment to an array component are illustrated by the following example program:<p>
<blockquote><pre>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 &lt; 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 =&gt; ");
                       x[indexThrow()] = rightThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sx + "[throw]=" + sy + " =&gt; ");
                       x[indexThrow()] = y;
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sx + "[" + j + "]=throw =&gt; ");
                       x[j] = rightThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sx + "[" + j + "]=" + sy + " =&gt; ");
                       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 =&gt; ");
                       arrayThrow()[indexThrow()] = rightThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[throw]=Thread =&gt; ");
                       arrayThrow()[indexThrow()] = new Thread();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[1]=throw =&gt; ");
                       arrayThrow()[1] = rightThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[1]=Thread =&gt; ");
                       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());
       }
}
</pre></blockquote><a name="238532"></a>
This program prints:<p>
<blockquote><pre>throw[throw]=throw =&gt; ArrayReferenceThrow
throw[throw]=Thread =&gt; ArrayReferenceThrow
throw[1]=throw =&gt; ArrayReferenceThrow
throw[1]=Thread =&gt; ArrayReferenceThrow
null[throw]=throw =&gt; IndexThrow
null[throw]=StringBuffer =&gt; IndexThrow
null[1]=throw =&gt; RightHandSideThrow
null[1]=StringBuffer =&gt; NullPointerException
null[throw]=throw =&gt; IndexThrow
null[throw]=StringBuffer =&gt; IndexThrow
null[1]=throw =&gt; RightHandSideThrow
null[1]=StringBuffer =&gt; NullPointerException
null[throw]=throw =&gt; IndexThrow
null[throw]=Thread =&gt; IndexThrow
null[9]=throw =&gt; RightHandSideThrow
null[9]=Thread =&gt; NullPointerException
null[throw]=throw =&gt; IndexThrow
null[throw]=Thread =&gt; IndexThrow
null[9]=throw =&gt; RightHandSideThrow
null[9]=Thread =&gt; NullPointerException
Objects[throw]=throw =&gt; IndexThrow
Objects[throw]=StringBuffer =&gt; IndexThrow
Objects[1]=throw =&gt; RightHandSideThrow
Objects[1]=StringBuffer =&gt; Okay!
Objects[throw]=throw =&gt; IndexThrow
Objects[throw]=Thread =&gt; IndexThrow
Objects[1]=throw =&gt; RightHandSideThrow
Objects[1]=Thread =&gt; Okay!
Objects[throw]=throw =&gt; IndexThrow
Objects[throw]=StringBuffer =&gt; IndexThrow
Objects[9]=throw =&gt; RightHandSideThrow
Objects[9]=StringBuffer =&gt; ArrayIndexOutOfBoundsException
Objects[throw]=throw =&gt; IndexThrow
Objects[throw]=Thread =&gt; IndexThrow
Objects[9]=throw =&gt; RightHandSideThrow
Objects[9]=Thread =&gt; ArrayIndexOutOfBoundsException
Threads[throw]=throw =&gt; IndexThrow
Threads[throw]=StringBuffer =&gt; IndexThrow
Threads[1]=throw =&gt; RightHandSideThrow
Threads[1]=StringBuffer =&gt; ArrayStoreException
Threads[throw]=throw =&gt; IndexThrow
Threads[throw]=Thread =&gt; IndexThrow
Threads[1]=throw =&gt; RightHandSideThrow
Threads[1]=Thread =&gt; Okay!
Threads[throw]=throw =&gt; IndexThrow
Threads[throw]=StringBuffer =&gt; IndexThrow
Threads[9]=throw =&gt; RightHandSideThrow
Threads[9]=StringBuffer =&gt; ArrayIndexOutOfBoundsException
Threads[throw]=throw =&gt; IndexThrow
Threads[throw]=Thread =&gt; IndexThrow
Threads[9]=throw =&gt; RightHandSideThrow
Threads[9]=Thread =&gt; ArrayIndexOutOfBoundsException
</pre></blockquote><a name="238840"></a>
The most interesting case of the lot is the one thirteenth from the end:<p>
<blockquote><pre>Threads[1]=StringBuffer =&gt; ArrayStoreException
</pre></blockquote><a name="264631"></a>
which indicates that the attempt to store a reference to a <code>StringBuffer</code> into an array whose components are of type <code>Thread</code> throws an <code>ArrayStoreException</code>. The code is type-correct at compile time: the assignment has a left-hand side of type <code>Object[]</code> and a right-hand side of type <code>Object</code>. At run time, the first actual argument to method <code>testFour</code> is a reference to an instance of "array of <code>Thread</code>" and the third actual argument is a reference to an instance of class <code>StringBuffer</code>.<p>
<a name="5304"></a>
<h3>15.26.2    Compound Assignment Operators</h3>
<a name="5305"></a>
All compound assignment operators require both operands to be of primitive type, except for <code>+=</code>, which allows the right-hand operand to be of any type if the left-hand operand is of type <code>String</code>.<p>
<a name="5306"></a>
A compound assignment expression of the form <i>E1</i> <i>op</i>= <i>E2</i> is equivalent to <i>E1</i> &#32;<code>=</code> &#32;<code>(</code><i>T</i><code>)((</code><i>E1</i><code>)</code> <i>op</i> <code>(</code><i>E2</i><code>))</code>, where <i>T</i> is the type of <i>E1</i>, except that <i>E1</i> is evaluated only once. Note that the implied cast to type <i>T</i> may be either an identity conversion <a href="conversions.doc.html#25209">(&#167;5.1.1)</a> or a narrowing primitive conversion <a href="conversions.doc.html#25363">(&#167;5.1.3)</a>. For example, the following code is correct:<p>
<pre><a name="236396"></a>
short x = 3;
<a name="236397"></a>x += 4.6;
</pre><a name="236398"></a>
and results in <code>x</code> having the value <code>7</code> because it is equivalent to:<p>
<pre><a name="236400"></a>
short x = 3;
<a name="249528"></a>x = (short)(x + 4.6);
</pre><a name="249529"></a>
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:<p>
<ul><a name="238396"></a>
<li>First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
<a name="238397"></a>
<li>Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238433"></a>
<li>Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see <a href="expressions.doc.html#5047">&#167;15.17.2</a>), then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="251178"></a>
<li>Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a> to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.
</ul><a name="238402"></a>
If the left-hand operand expression is an array access expression <a href="expressions.doc.html#239587">(&#167;15.13)</a>, then many steps are required:<p>
<ul><a name="238403"></a>
<li>First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
<a name="238404"></a>
<li>Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
<a name="238449"></a>
<li>Otherwise, if the value of the array reference subexpression is <code>null</code>, then no assignment occurs and a <code>NullPointerException</code> &#32;is thrown.
<a name="238450"></a>
<li>Otherwise, the value of the array reference subexpression indeed refers to an array. If the value of the index subexpression is less than zero, or greater than &#32;or equal to the length of the array, then no assignment occurs and an <code>ArrayIndexOutOfBoundsException</code> &#32;is thrown.
<a name="238405"></a>
<li>Otherwise, the value of the index subexpression is used to select a component of the array referred to by the value of the array reference subexpression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. (For a simple assignment operator, the evaluation of the right-hand operand occurs before the checks of the array reference subexpression and the index subexpression, but for a compound assignment operator, the evaluation of the right-hand operand occurs after these checks.)
<a name="238408"></a>
<li>Otherwise, consider the array component selected in the previous step, whose value was saved. This component is a variable; call its type <i>S</i>. Also, let <i>T</i> be the type of the left-hand operand of the assignment operator as determined at compile time.
<ul>
<a name="238409"></a>
<li>If <i>T</i> is a primitive type, then <i>S</i> is necessarily the same as <i>T</i>.
<ul>
<a name="238472"></a>
<li>The saved value of the array component and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see <a href="expressions.doc.html#5047">&#167;15.17.2</a>), then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="251182"></a>
<li>Otherwise, the result of the binary operation is converted to the type of the selected array component, subjected to value set conversion <a href="conversions.doc.html#184225">(&#167;5.1.8)</a> to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the array component.
</ul>
<a name="238410"></a>
<li>If <i>T</i> is a reference type, then it must be <code>String</code>. Because class <code>String</code> is a <code>final</code> class, <i>S</i> must also be <code>String</code>. Therefore the run-time check that is sometimes required for the simple assignment operator is never required for a compound assignment operator.
<ul>
<a name="238488"></a>
<li>The saved value of the array component and the value of the right-hand operand are used to perform the binary operation (string concatenation) indicated by the compound assignment operator (which is necessarily <code>+=</code>). If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
</ul>
</ul>
</ul><a name="264636"></a>
Otherwise, the <code>String</code> result of the binary operation is stored into the array component.<p>
<a name="238860"></a>
The rules for compound assignment to an array component are illustrated by the following example program:<p>
<blockquote><pre>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 &lt; 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 =&gt; ");
                       x[indexThrow()] += stringThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sz + "[throw]+=throw =&gt; ");
                       z[indexThrow()] += doubleThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sx + "[throw]+=\"heh\" =&gt; ");
                       x[indexThrow()] += "heh";
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sz + "[throw]+=12345 =&gt; ");
                       z[indexThrow()] += 12345;
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sx + "[" + j + "]+=throw =&gt; ");
                       x[j] += stringThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sz + "[" + j + "]+=throw =&gt; ");
                       z[j] += doubleThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sx + "[" + j + "]+=\"heh\" =&gt; ");
                       x[j] += "heh";
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print(sz + "[" + j + "]+=12345 =&gt; ");
                       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 =&gt; ");
                       stringsThrow()[indexThrow()] += stringThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[throw]+=throw =&gt; ");
                       doublesThrow()[indexThrow()] += doubleThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[throw]+=\"heh\" =&gt; ");
                       stringsThrow()[indexThrow()] += "heh";
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[throw]+=12345 =&gt; ");
                       doublesThrow()[indexThrow()] += 12345;
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[1]+=throw =&gt; ");
                       stringsThrow()[1] += stringThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[1]+=throw =&gt; ");
                       doublesThrow()[1] += doubleThrow();
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[1]+=\"heh\" =&gt; ");
                       stringsThrow()[1] += "heh";
                       System.out.println("Okay!");
               } catch (Throwable e) { System.out.println(name(e)); }
               try {
                       System.out.print("throw[1]+=12345 =&gt; ");
                       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);
       }
}
</pre></blockquote><a name="238992"></a>
This program prints:<p>
<blockquote><pre>throw[throw]+=throw =&gt; ArrayReferenceThrow
throw[throw]+=throw =&gt; ArrayReferenceThrow
throw[throw]+="heh" =&gt; ArrayReferenceThrow
throw[throw]+=12345 =&gt; ArrayReferenceThrow
throw[1]+=throw =&gt; ArrayReferenceThrow
throw[1]+=throw =&gt; ArrayReferenceThrow
throw[1]+="heh" =&gt; ArrayReferenceThrow
throw[1]+=12345 =&gt; ArrayReferenceThrow
null[throw]+=throw =&gt; IndexThrow
null[throw]+=throw =&gt; IndexThrow
null[throw]+="heh" =&gt; IndexThrow
null[throw]+=12345 =&gt; IndexThrow
null[1]+=throw =&gt; NullPointerException
null[1]+=throw =&gt; NullPointerException
null[1]+="heh" =&gt; NullPointerException
null[1]+=12345 =&gt; NullPointerException
null[throw]+=throw =&gt; IndexThrow
null[throw]+=throw =&gt; IndexThrow
null[throw]+="heh" =&gt; IndexThrow
null[throw]+=12345 =&gt; IndexThrow
null[9]+=throw =&gt; NullPointerException
null[9]+=throw =&gt; NullPointerException
null[9]+="heh" =&gt; NullPointerException
null[9]+=12345 =&gt; NullPointerException
Strings[throw]+=throw =&gt; IndexThrow
doubles[throw]+=throw =&gt; IndexThrow
Strings[throw]+="heh" =&gt; IndexThrow
doubles[throw]+=12345 =&gt; IndexThrow
Strings[1]+=throw =&gt; RightHandSideThrow
doubles[1]+=throw =&gt; RightHandSideThrow
Strings[1]+="heh" =&gt; Okay!
doubles[1]+=12345 =&gt; Okay!
Strings[throw]+=throw =&gt; IndexThrow
doubles[throw]+=throw =&gt; IndexThrow
Strings[throw]+="heh" =&gt; IndexThrow
doubles[throw]+=12345 =&gt; IndexThrow
Strings[9]+=throw =&gt; ArrayIndexOutOfBoundsException
doubles[9]+=throw =&gt; ArrayIndexOutOfBoundsException
Strings[9]+="heh" =&gt; ArrayIndexOutOfBoundsException
doubles[9]+=12345 =&gt; ArrayIndexOutOfBoundsException
</pre></blockquote><a name="239051"></a>
The most interesting cases of the lot are tenth and eleventh from the end:<p>
<blockquote><pre>Strings[1]+=throw =&gt; RightHandSideThrow
doubles[1]+=throw =&gt; RightHandSideThrow
</pre></blockquote><a name="238861"></a>
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.<p>
<a name="240007"></a>
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:<p>
<blockquote><pre>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]);
       }
}
</pre></blockquote><a name="240021"></a>
This program prints:<p>
<blockquote><pre>k==25 and a[0]==25
</pre></blockquote><a name="240027"></a>
The value <code>1</code> of <code>k</code> is saved by the compound assignment operator <code>+=</code> before its right-hand operand <code>(k</code> <code>=</code> <code>4)</code> <code>*</code> <code>(k</code> <code>+</code> <code>2)</code> is evaluated. Evaluation of this right-hand operand then assigns <code>4</code> to <code>k</code>, calculates the value <code>6</code> for <code>k</code> <code>+</code> <code>2</code>, and then multiplies <code>4</code> &#32;by &#32;<code>6</code> to get <code>24</code>. This is added to the saved value <code>1</code> to get <code>25</code>, which is then stored into <code>k</code> by the <code>+=</code> operator. An identical analysis applies to the case that uses <code>a[0]</code>. In short, the statements<p>
<blockquote><pre>k += (k = 4) * (k + 2);
a[0] += (a[0] = 4) * (a[0] + 2);
</pre></blockquote><a name="240066"></a>
behave in exactly the same manner as the statements:<p>
<blockquote><pre>k = k + (k = 4) * (k + 2);
a[0] = a[0] + (a[0] = 4) * (a[0] + 2);
</pre></blockquote><a name="5308"></a>
<h2>15.27    Expression</h2>
<a name="5309"></a>
An <em>Expression</em> is any assignment expression:<p>
<ul><pre>
<em>Expression:
       AssignmentExpression</em>
</ul></pre>
<a name="264651"></a>
Unlike C and C++, the Java programming language has no comma operator.<p>
</pre></ul><a name="5313"></a>
<h2>15.28    Constant Expression</h2>
<ul><pre>
<em>ConstantExpression:
       Expression</em>
</pre></ul><a name="5314"></a>
A compile-time <em>constant expression</em> is an expression denoting a value of primitive type or a <code>String</code> that is composed using only the following:<p>
<ul><a name="236320"></a>
<li>Literals of primitive type and literals of type <code>String</code>
<a name="236323"></a>
<li>Casts to primitive types and casts to type <code>String</code>
<a name="236324"></a>
<li>The unary operators <code>+</code>, <code>-</code>, <code>~</code>, and <code>! </code>(but not <code>++</code> or <code>--</code>)
<a name="239222"></a>
<li>The multiplicative operators <code>*</code>, <code>/</code>, and <code>%</code>
<a name="239261"></a>
<li>The additive operators <code>+</code> and <code>-</code>
<a name="239263"></a>
<li>The shift operators <code>&lt;&lt;</code>, <code>&gt;&gt;</code>, and <code>&gt;&gt;&gt;</code>
<a name="239226"></a>
<li>The relational operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;= </code>(but not <code>instanceof</code>)
<a name="239228"></a>
<li>The equality operators <code>==</code> and <code>!=</code>
<a name="239255"></a>
<li>The bitwise and logical operators <code>&amp;</code>, <code>^</code>, and <code>|</code>
<a name="239257"></a>
<li>The conditional-and operator <code>&amp;&amp;</code> and the conditional-or operator <code>||</code>
<a name="236327"></a>
<li>The ternary conditional operator <code>?</code>&#32;<code>:</code>
<a name="8720"></a>
<li>Simple names that refer to <code>final</code> variables whose initializers are constant expressions
<a name="239286"></a>
<li>Qualified names of the form <em>TypeName</em> <code>.</code> <em>Identifier</em> that refer to <code>final</code> variables whose initializers are constant expressions
</ul><a name="5315"></a>
Compile-time constant expressions are used in <code>case</code> labels in <code>switch</code> statements <a href="statements.doc.html#35518">(&#167;14.10)</a> and have a special significance for assignment conversion <a href="conversions.doc.html#184206">(&#167;5.2)</a>.<p>
<a name="264656"></a>
A compile-time constant expression is always treated as FP-strict <a href="expressions.doc.html#249198">(&#167;15.4)</a>, even if it occurs in a context where a non-constant expression would not be considered to be FP-strict.<p>
<a name="236407"></a>
Examples of constant expressions:<p>
<blockquote><pre>true
(short)(1*2*3*4*5*6)
Integer.MAX_VALUE / 2
2.0 * Math.PI
"The integer " + Long.MAX_VALUE + " is mighty big."
</pre></blockquote>

<hr>
<table border="0" width="100%">
<tr>
<td><a href="jTOC.doc.html">Contents</a> | <a href="statements.doc.html">Prev</a> | <a href="defAssign.doc.html">Next</a> | <a href="jIX.fm.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">Second Edition</font></td></tr></table>
<i><a href="jcopyright.doc.html">Copyright</a> &#169 2000 Sun Microsystems, Inc.
All rights reserved</i>
<br>
Please send any comments or corrections to <a href="mailto:[email protected]">[email protected]</a>
</font>
</body></html>