-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter-15.txt
5340 lines (3219 loc) · 314 KB
/
chapter-15.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Chapter 15. Expressions
Table of Contents
15.1. Evaluation, Denotation, and Result
15.2. Forms of Expressions
15.3. Type of an Expression
15.4. Floating-point Expressions
15.5. Expressions and Run-Time Checks
15.6. Normal and Abrupt Completion of Evaluation
15.7. Evaluation Order
15.7.1. Evaluate Left-Hand Operand First
15.7.2. Evaluate Operands before Operation
15.7.3. Evaluation Respects Parentheses and Precedence
15.7.4. Argument Lists are Evaluated Left-to-Right
15.7.5. Evaluation Order for Other Expressions
15.8. Primary Expressions
15.8.1. Lexical Literals
15.8.2. Class Literals
15.8.3. this
15.8.4. Qualified this
15.8.5. Parenthesized Expressions
15.9. Class Instance Creation Expressions
15.9.1. Determining the Class being Instantiated
15.9.2. Determining Enclosing Instances
15.9.3. Choosing the Constructor and its Arguments
15.9.4. Run-Time Evaluation of Class Instance Creation Expressions
15.9.5. Anonymous Class Declarations
15.9.5.1. Anonymous Constructors
15.10. Array Creation and Access Expressions
15.10.1. Array Creation Expressions
15.10.2. Run-Time Evaluation of Array Creation Expressions
15.10.3. Array Access Expressions
15.10.4. Run-Time Evaluation of Array Access Expressions
15.11. Field Access Expressions
15.11.1. Field Access Using a Primary
15.11.2. Accessing Superclass Members using super
15.12. Method Invocation Expressions
15.12.1. Compile-Time Step 1: Determine Type to Search
15.12.2. Compile-Time Step 2: Determine Method Signature
15.12.2.1. Identify Potentially Applicable Methods
15.12.2.2. Phase 1: Identify Matching Arity Methods Applicable by Strict Invocation
15.12.2.3. Phase 2: Identify Matching Arity Methods Applicable by Loose Invocation
15.12.2.4. Phase 3: Identify Methods Applicable by Variable Arity Invocation
15.12.2.5. Choosing the Most Specific Method
15.12.2.6. Method Invocation Type
15.12.3. Compile-Time Step 3: Is the Chosen Method Appropriate?
15.12.4. Run-Time Evaluation of Method Invocation
15.12.4.1. Compute Target Reference (If Necessary)
15.12.4.2. Evaluate Arguments
15.12.4.3. Check Accessibility of Type and Method
15.12.4.4. Locate Method to Invoke
15.12.4.5. Create Frame, Synchronize, Transfer Control
15.13. Method Reference Expressions
15.13.1. Compile-Time Declaration of a Method Reference
15.13.2. Type of a Method Reference
15.13.3. Run-Time Evaluation of Method References
15.14. Postfix Expressions
15.14.1. Expression Names
15.14.2. Postfix Increment Operator ++
15.14.3. Postfix Decrement Operator --
15.15. Unary Operators
15.15.1. Prefix Increment Operator ++
15.15.2. Prefix Decrement Operator --
15.15.3. Unary Plus Operator +
15.15.4. Unary Minus Operator -
15.15.5. Bitwise Complement Operator ~
15.15.6. Logical Complement Operator !
15.16. Cast Expressions
15.17. Multiplicative Operators
15.17.1. Multiplication Operator *
15.17.2. Division Operator /
15.17.3. Remainder Operator %
15.18. Additive Operators
15.18.1. String Concatenation Operator +
15.18.2. Additive Operators (+ and -) for Numeric Types
15.19. Shift Operators
15.20. Relational Operators
15.20.1. Numerical Comparison Operators <, <=, >, and >=
15.20.2. The instanceof Operator
15.21. Equality Operators
15.21.1. Numerical Equality Operators == and !=
15.21.2. Boolean Equality Operators == and !=
15.21.3. Reference Equality Operators == and !=
15.22. Bitwise and Logical Operators
15.22.1. Integer Bitwise Operators &, ^, and |
15.22.2. Boolean Logical Operators &, ^, and |
15.23. Conditional-And Operator &&
15.24. Conditional-Or Operator ||
15.25. Conditional Operator ? :
15.25.1. Boolean Conditional Expressions
15.25.2. Numeric Conditional Expressions
15.25.3. Reference Conditional Expressions
15.26. Assignment Operators
15.26.1. Simple Assignment Operator =
15.26.2. Compound Assignment Operators
15.27. Lambda Expressions
15.27.1. Lambda Parameters
15.27.2. Lambda Body
15.27.3. Type of a Lambda Expression
15.27.4. Run-Time Evaluation of Lambda Expressions
15.28. switch Expressions
15.28.1. The Switch Block of a switch Expression
15.28.2. Run-Time Evaluation of switch Expressions
15.29. Constant Expressions
Much of the work in a program is done by evaluating expressions, either for their side effects, such as assignments to variables, or for their values, which can be used as arguments or operands in larger expressions, or to affect the execution sequence in statements, or both.
This chapter specifies the meanings of expressions and the rules for their evaluation.
15.1. Evaluation, Denotation, and Result
When an expression in a program is evaluated (executed), the result denotes one of three things:
A variable (§4.12) (in C, this would be called an lvalue)
A value (§4.2, §4.3)
Nothing (the expression is said to be void)
If an expression denotes a variable, and a value is required for use in further evaluation, then the value of that variable is used. In this context, if the expression denotes a variable or a value, we may speak simply of the value of the expression.
An expression denotes nothing if and only if it is a method invocation (§15.12) that invokes a method that does not return a value, that is, a method declared void (§8.4). Such an expression can be used only as an expression statement (§14.8) or as the single expression of a lambda body (§15.27.2), because every other context in which an expression can appear requires the expression to denote something. An expression statement or lambda body 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.
Evaluation of an expression can produce side effects, because expressions may contain embedded assignments, increment operators, decrement operators, method invocations, and, in switch expressions, arbitrary statements.
An expression occurs in either:
The declaration of some class or interface that is being declared: in a field initializer, in a static initializer, in an instance initializer, in a constructor declaration, in a method declaration, or in an annotation.
An annotation on the declaration of a module, a package, or a top level class or interface.
15.2. Forms of Expressions
Expressions can be broadly categorized into one of the following syntactic forms:
Expression names (§6.5.6)
Primary expressions (§15.8 - §15.13)
Unary operator expressions (§15.14 - §15.16)
Binary operator expressions (§15.17 - §15.24, and §15.26)
Ternary operator expressions (§15.25)
Lambda expressions (§15.27)
switch expressions (§15.28)
Precedence among operators is managed by a hierarchy of grammar productions. The lowest precedence operator is the arrow of a lambda expression (->), followed by the assignment operators. Thus, all expressions are syntactically included in the LambdaExpression and AssignmentExpression nonterminals:
Expression:
LambdaExpression
AssignmentExpression
When some expressions appear in certain contexts, they are considered poly expressions. The following forms of expressions may be poly expressions:
Parenthesized expressions (§15.8.5)
Class instance creation expressions (§15.9)
Method invocation expressions (§15.12)
Method reference expressions (§15.13)
Conditional expressions (§15.25)
Lambda expressions (§15.27)
switch expressions (§15.28)
The rules determining whether an expression of one of these forms is a poly expression are given in the individual sections that specify these forms of expressions.
Expressions that are not poly expressions are standalone expressions. Standalone expressions are expressions of the forms above when determined not to be poly expressions, as well as all expressions of all other forms. Expressions of all other forms are said to have a standalone form.
Some expressions have a value that can be determined at compile time. These are constant expressions (§15.29).
15.3. Type of an Expression
If an expression denotes a variable or a value, then the expression has a type known at compile time. The type of a standalone expression can be determined entirely from the contents of the expression; in contrast, the type of a poly expression may be influenced by the expression's target type (§5 (Conversions and Contexts)). The rules for determining the type of an expression are explained separately below for each kind of expression.
The value of an expression is assignment compatible (§5.2) with the type of the expression, unless heap pollution occurs (§4.12.2).
Likewise, the value stored in a variable is always compatible with the type of the variable, unless heap pollution occurs.
In other words, the value of an expression whose type is T is always suitable for assignment to a variable of type T.
Note that if the type of an expression is a class type which names the class C, then the declaration of class C as final or sealed (§8.1.1.2) has implications for the value of the expression:
If C is final, then the expression is guaranteed to have a value that is either (i) the null reference, or (ii) an object whose class is C itself, because final classes have no subclasses.
If C is sealed, then the expression is guaranteed to have a value that is either (i) the null reference, (ii) an object whose class is C itself, or (iii) assignment compatible with one of the permitted direct subclasses of C (§8.1.6).
If C is freely extensible, then the expression is guaranteed to have a value that is either (i) the null reference, (ii) an object whose class is C itself, or (iii) assignment compatible with C.
15.4. Floating-point Expressions
A floating-point expression is an expression whose type is float or double (§4.2.3). Floating-point expressions of type float denote values that exactly correspond to the values representable in the 32-bit IEEE 754 binary32 format. Floating-point expressions of type double denote values that exactly correspond to the values representable in the 64-bit IEEE 754 binary64 format.
Many of the comparison and numerical operators of the Java programming language that can be used to form floating-point expressions correspond to IEEE 754 operations, as do the conversions that act on floating-point values (Table 15.4-A).
Table 15.4-A. Correspondence with IEEE 754 operations
Operator/Conversion IEEE 754 operation
The numerical comparison operators <, <=, >, and >= (§15.20.1) compareQuietLess, compareQuietLessEqual, compareQuietGreater, compareQuietGreaterEqual
The numerical equality operators == and != (§15.21.1) compareQuietEqual, compareQuietNotEqual
The unary minus operator - (§15.15.4) negate
The multiplicative operators * and / (§15.17.1, §15.17.2) multiplication, division
The additive operators + and - (§15.18.2) addition, subtraction
Widening primitive conversion from an integral type (§5.1.2) convertFromInt
Narrowing primitive conversion to an integral type (§5.1.3) convertToIntegerTowardZero
Conversion between float and double convertFormat
The floating-point remainder operator % (§15.17.3) does not correspond to the IEEE 754 remainder operation.
Some IEEE 754 operations without corresponding operators in the Java programming language are provided via methods in the Math and StrictMath classes, including the sqrt method for the IEEE 754 squareRoot operation, the fma method for the IEEE 754 fusedMultiplyAdd operation, and the IEEEremainder method for the IEEE 754 remainder operation.
The Java programming language requires support of IEEE 754 subnormal floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations do not "flush to zero" if the calculated result is a subnormal number.
The result of a floating-point operator of the Java programming language must match the result of the corresponding IEEE 754 operation on the same operands. For finite results, this implies the sign, significand, and exponent of the floating-point result must all be those specified by IEEE 754.
The requirement for matching sign, significand, and exponent precludes some transformations that might be allowed if floating-point behavior was less precisely specified. For example, -x cannot generally be replaced by (0.0 - x) because the sign of the result will differ if x is -0.0. Also, other possibly value-changing transformation such as replacing (a * b + c) with a call to a fused multiply-accumulate library method are not allowed unless the result can be proven to be identical.
There are no circumstances where the evaluation of a floating-point expression may use intermediate results that have more precision or more exponent range than indicated by the expression's type.
A floating-point operation that overflows produces a signed infinity.
A floating-point operation that underflows produces a subnormal value or a signed zero.
A floating-point operation that has no unique mathematically defined result produces NaN.
All numeric operations with NaN as an operand produce NaN as a result.
Since NaN is unordered, any numerical comparison operation involving one or two NaNs returns false, any == comparison involving NaN returns false, and any != comparison involving NaN returns true.
Floating-point arithmetic is an approximation to real arithmetic. While there are an infinite number of real numbers, a particular floating-point format only has a finite number of values. In the Java programming language, a rounding policy is a function used to map from a real number to a floating-point value in a given format. For real numbers in the representable range of a floating-point format, a continuous segment of the real number line is mapped to a single floating-point value. The real number whose value is numerically equal to a floating-point value is mapped to that floating-point value; for example, the real number 1.5 is mapped to the floating-point value 1.5 in a given format. The Java programming language defines two rounding policies, as follows:
The round to nearest rounding policy applies to all floating-point operators except for (i) conversion to an integer value, and (ii) floating-point remainder. Under the round to nearest rounding policy, inexact results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, then the value whose least significant bit is zero is chosen.
The round to nearest rounding policy corresponds to the default rounding-direction attribute for binary arithmetic in IEEE 754, roundTiesToEven.
The roundTiesToEven rounding-direction attribute was known as the "round to nearest" rounding mode in the 1985 version of the IEEE 754 Standard. The rounding policy in the Java programming language is named after this rounding mode.
The round toward zero rounding policy applies to (i) conversion of a floating-point value to an integer value (§5.1.3), and (ii) floating-point remainder (§15.17.3). Under the round toward zero rounding policy, inexact results are rounded to the nearest representable value that is not greater in magnitude than the infinitely precise result. For conversion to integer, the round toward zero rounding policy is equivalent to truncation where fractional significand bits are discarded.
The round toward zero rounding policy corresponds to the roundTowardZero rounding-direction attribute for binary arithmetic in IEEE 754.
The roundTowardZero rounding-direction attribute was known as the "round toward zero" rounding mode in the 1985 version of the IEEE 754 Standard. The rounding policy in the Java programming language is named after this rounding mode.
The Java programming language requires that every floating-point operator rounds its floating-point result to the result precision. The rounding policy used for each floating-point operator is either round to nearest or round toward zero, as specified above.
Java 1.0 and 1.1 required strict evaluation of floating-point expressions. Strict evaluation means that each float operand corresponds to a value representable in the IEEE 754 binary32 format, each double operand corresponds to a value representable in the IEEE 754 binary64 format, and each floating-point operator with a corresponding IEEE 754 operation matches the IEEE 754 result for the same operands.
Strict evaluation provides predictable results, but caused performance problems in the Java Virtual Machine implementations for some processor families common in the Java 1.0/1.1 era. Consequently, in Java 1.2 through Java SE 16, the Java SE Platform allowed a Java Virtual Machine implementation to have one or two value sets associated with each floating-point type. The float type was associated with the float value set and the float-extended-exponent value set, while the double type was associated with the double value set and the double-extended-exponent value set. The float value set corresponded to the values representable in the IEEE 754 binary32 format; the float-extended-exponent value set had the same number of precision bits but larger exponent range. Similarly, the double value set corresponded to the values representable in the IEEE 754 binary64 format; the double-extended-exponent value set had the same number of precision bits but larger exponent range. Allowing use of the extended-exponent value sets by default ameliorated the performance problems on some processor families.
For compatibility, Java 1.2 allowed the programmer to forbid an implementation from using the extended-exponent value sets. The programmer expressed this by placing the strictfp modifier on the declaration of a class, interface, or method. strictfp constrained the floating-point semantics of any enclosed expressions to use the float value set for float expressions and the double value set for double expressions, ensuring the results of such expressions were fully predictable. Code modified by strictfp thus had the same floating-point semantics as specified in Java 1.0 and 1.1.
In Java SE 17 and later, the Java SE Platform always requires strict evaluation of floating-point expressions. Newer members of the processor families that had performance problems implementing strict evaluation no longer have that difficulty. This specification no longer associates float and double with the four value sets described above, and the strictfp modifier no longer affects the evaluation of floating-point expressions. For compatibility, strictfp remains a keyword in Java SE 23 (§3.8) and continues to have restrictions on its use (§8.4.3, §9.4), although Java compilers are encouraged to warn the programmer about its obsolete status. Future versions of the Java programming language may redefine or remove the strictfp keyword.
15.5. Expressions and Run-Time Checks
If the type of an expression is a primitive type, then the value of the expression is of that same primitive type.
If the type of an expression is a reference type, then the class of the referenced object, or even whether the value is a reference to an object rather than null, is not necessarily known at compile time. There are a few places in the Java programming language where the actual class of a referenced object affects program execution in a manner that cannot be deduced from the type of the expression. They are as follows:
Method invocation (§15.12). The particular method used for an invocation o.m(...) is chosen based on the methods that are part of the class or interface that is the type of o. For instance methods, the class of the object referenced by the run-time value of o 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 m method.)
The instanceof operator (§15.20.2). An expression whose type is a reference type may be tested using instanceof to find out whether the class of the object referenced by the run-time value of the expression may be converted to some other reference type.
Casting (§15.16). 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 operator. 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, cannot be converted to the target type.
Assignment to an array component of reference type (§10.5, §15.13, §15.26.1). The type-checking rules allow the array type S[] to be treated as a subtype of T[] if S is a subtype of T, but this requires a run-time check for assignment to an array component, similar to the check performed for a cast.
Exception handling (§14.20). An exception is caught by a catch clause only if the class of the thrown exception object is an instanceof the type of the formal parameter of the catch clause.
Situations where the class of an object is not statically known may lead to run-time type errors.
In addition, there are situations where the statically known type may not be accurate at run time. Such situations can arise in a program that gives rise to compile-time unchecked warnings. Such warnings are given in response to operations that cannot be statically guaranteed to be safe, and cannot immediately be subjected to dynamic checking because they involve non-reifiable types (§4.7). As a result, dynamic checks later in the course of program execution may detect inconsistencies and result in run-time type errors.
A run-time type error can occur only in these situations:
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 (§5.5, §15.16); in this case a ClassCastException is thrown.
In an automatically generated cast introduced to ensure the validity of an operation on a non-reifiable type (§4.7).
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 (§10.5, §15.13, §15.26.1); in this case an ArrayStoreException is thrown.
When an exception is not caught by any catch clause of a try statement (§14.20); in this case the thread of control that encountered the exception first attempts to invoke an uncaught exception handler (§11.3) and then terminates.
15.6. Normal and Abrupt Completion of Evaluation
Every expression has a normal mode of evaluation in which certain computational steps are carried out. The following sections describe the normal mode of evaluation for each kind of expression.
If all the steps are carried out without an exception being thrown, the expression is said to complete normally.
If, however, evaluation of an expression throws an exception, then the expression is said to complete abruptly. An abrupt completion always has an associated reason, which is always a throw with a given value.
Run-time exceptions are thrown by the predefined operators as follows:
A class instance creation expression (§15.9.4), array creation expression (§15.10.2), method reference expression (§15.13.3), array initializer expression (§10.6), string concatenation operator expression (§15.18.1), or lambda expression (§15.27.4) throws an OutOfMemoryError if there is insufficient memory available.
An array creation expression (§15.10.2) throws a NegativeArraySizeException if the value of any dimension expression is less than zero.
An array access expression (§15.10.4) throws a NullPointerException if the value of the array reference expression is null.
An array access expression (§15.10.4) throws an ArrayIndexOutOfBoundsException if the value of the array index expression is negative or greater than or equal to the length of the array.
A field access expression (§15.11) throws a NullPointerException if the value of the object reference expression is null.
A method invocation expression (§15.12) that invokes an instance method throws a NullPointerException if the target reference is null.
A cast expression (§15.16) throws a ClassCastException if a cast is found to be impermissible at run time.
An integer division (§15.17.2) or integer remainder (§15.17.3) operator throws an ArithmeticException if the value of the right-hand operand expression is zero.
An assignment to an array component of reference type (§15.26.1), a method invocation expression (§15.12), or a prefix or postfix increment (§15.14.2, §15.15.1) or decrement operator (§15.14.3, §15.15.2) may all throw an OutOfMemoryError as a result of boxing conversion (§5.1.7).
An assignment to an array component of reference type (§15.26.1) throws an ArrayStoreException when the value to be assigned is not compatible with the component type of the array (§10.5).
A switch expression (§15.28) or enhanced switch statement (§14.11.2) throws a MatchException if no switch label applies to the value of the selector expression.
A method invocation expression can also result in an exception being thrown if an exception occurs that causes execution of the method body to complete abruptly.
A class instance creation expression can also result in an exception being thrown if an exception occurs that causes execution of the constructor to complete abruptly.
Various linkage and virtual machine errors may also occur during the evaluation of an expression. By their nature, such errors are difficult to predict and difficult to handle.
If an exception occurs, then evaluation of one or more expressions may be terminated before all steps of their normal mode of evaluation are complete; such expressions are said to complete abruptly.
If evaluation of an expression requires evaluation of a subexpression, then 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.
The terms "complete normally" and "complete abruptly" are also applied to the execution of statements (§14.1). A statement may complete abruptly for a variety of reasons, not just because an exception is thrown.
15.7. Evaluation Order
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.
15.7.1. Evaluate Left-Hand Operand First
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation.
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.
Example 15.7.1-1. Left-Hand Operand Is Evaluated First
In the following program, the * operator has a left-hand operand that contains an assignment to a variable and a right-hand operand that contains a reference to the same variable. The value produced by the reference will reflect the fact that the assignment occurred first.
class Test1 {
public static void main(String[] args) {
int i = 2;
int j = (i=3) * i;
System.out.println(j);
}
}
This program produces the output:
9
It is not permitted for evaluation of the * operator to produce 6 instead of 9.
Example 15.7.1-2. Implicit Left-Hand Operand In Operator Of Compound Assigment
In the following program, the two assignment statements both fetch and remember the value of the left-hand operand, which is 9, before the right-hand operand of the addition operator is evaluated, at which point the variable is set to 3.
class Test2 {
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);
}
}
This program produces the output:
12
12
It is not permitted for either assignment (compound for a, simple for b) to produce the result 6.
See also the example in §15.26.2.
Example 15.7.1-3. Abrupt Completion of Evaluation of the Left-Hand Operand
class Test3 {
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!");
}
}
This program produces the output:
java.lang.Exception: I'm outta here!
Now j = 1
That is, the left-hand operand forgetIt() of the operator / throws an exception before the right-hand operand is evaluated and its embedded assignment of 2 to j occurs.
15.7.2. Evaluate Operands before Operation
The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.
If the binary operator is an integer division / (§15.17.2) or integer remainder % (§15.17.3), then its execution may raise an ArithmeticException, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.
Example 15.7.2-1. Evaluation of Operands Before Operation
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!");
}
}
This program produces the output:
java.lang.Exception: Shuffle off to Buffalo!
and not:
java.lang.ArithmeticException: / by zero
since no part of the division operation, including signaling of a divide-by-zero exception, may appear to occur before the invocation of loseBig completes, even though the implementation may be able to detect or infer that the division operation would certainly result in a divide-by-zero exception.
15.7.3. Evaluation Respects Parentheses and Precedence
The Java programming language respects the order of evaluation indicated explicitly by parentheses and implicitly by operator precedence.
An implementation of the Java programming language may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects, even in the presence of multiple threads of execution (using the thread execution model in §17 (Threads and Locks)), for all possible computational values that might be involved.
In the case of floating-point calculations, this rule applies also for infinity and not-a-number (NaN) values.
For example, !(x<y) may not be rewritten as x>=y, because these expressions have different values if either x or y is NaN or both are NaN.
Specifically, floating-point calculations that appear to be mathematically associative are unlikely to be computationally associative. Such computations must not be naively reordered.
For example, it is not correct for a Java compiler to rewrite 4.0*x*0.5 as 2.0*x; while roundoff happens not to be an issue here, there are large values of x for which the first expression produces infinity (because of overflow) but the second expression produces a finite result.
So, for example, the test program:
class Test {
public static void main(String[] args) {
double d = 8E307;
System.out.println(4.0 * d * 0.5);
System.out.println(2.0 * d);
}
}
prints:
Infinity
1.6E308
because the first expression overflows and the second does not.
In contrast, integer addition and multiplication are provably associative in the Java programming language.
For example a+b+c, where a, b, and c are local variables (this simplifying assumption avoids issues involving multiple threads and volatile variables), will always produce the same answer whether evaluated as (a+b)+c or a+(b+c); if the expression b+c occurs nearby in the code, a smart Java compiler may be able to use this common subexpression.
15.7.4. Argument Lists are Evaluated Left-to-Right
In a method or constructor invocation or class instance creation expression, argument expressions may appear within the parentheses, separated by commas. Each argument expression appears to be fully evaluated before any part of any argument expression to its right.
If evaluation of an argument expression completes abruptly, no part of any argument expression to its right appears to have been evaluated.
Example 15.7.4-1. Evaluation Order At Method Invocation
class Test1 {
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);
}
}
This program produces the output:
going, going, gone
because the assignment of the string "gone" to s occurs after the first two arguments to print3 have been evaluated.
Example 15.7.4-2. Abrupt Completion of Argument Expression
class Test2 {
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 test(int a, int b, int c) {
return a + b + c;
}
static int oops() throws Exception {
throw new Exception("oops");
}
}
This program produces the output:
java.lang.Exception: oops, id=1
because the assignment of 3 to id is not executed.
15.7.5. Evaluation Order for Other Expressions
The order of evaluation for some expressions is not completely covered by these general rules, because these expressions may raise exceptional conditions at times that must be specified. See the detailed explanations of evaluation order for the following kinds of expressions:
class instance creation expressions (§15.9.4)
array creation expressions (§15.10.2)
array access expressions (§15.10.4)
method invocation expressions (§15.12.4)
method reference expressions (§15.13.3)
assignments involving array components (§15.26)
lambda expressions (§15.27.4)
15.8. Primary Expressions
Primary expressions include most of the simplest kinds of expressions, from which all others are constructed: literals, object creations, field accesses, method invocations, method references, and array accesses. A parenthesized expression is also treated syntactically as a primary expression.
Primary:
PrimaryNoNewArray
ArrayCreationExpression
PrimaryNoNewArray:
Literal
ClassLiteral
this
TypeName . this
( Expression )
ClassInstanceCreationExpression
FieldAccess
ArrayAccess
MethodInvocation
MethodReference
This part of the grammar of the Java programming language is unusual, in two ways. First, one might expect simple names, such as names of local variables and method parameters, to be primary expressions. For technical reasons, names are grouped together with primary expressions a little later when postfix expressions are introduced (§15.14).
The technical reasons have to do with allowing left-to-right parsing of Java programs with only one-token lookahead. Consider the expressions (z[3]) and (z[]). The first is a parenthesized array access (§15.10.3) and the second is the start of a cast (§15.16). At the point that the look-ahead symbol is [, a left-to-right parse will have reduced the z to the nonterminal Name. In the context of a cast we prefer not to have to reduce the name to a Primary, but if Name were one of the alternatives for Primary, then we could not tell whether to do the reduction (that is, we could not determine whether the current situation would turn out to be a parenthesized array access or a cast) without looking ahead two tokens, to the token following the [. The grammar presented here avoids the problem by keeping Name and Primary separate and allowing either in certain other syntax rules (those for ClassInstanceCreationExpression, MethodInvocation, ArrayAccess, and PostfixExpression, though not FieldAccess because it uses an identifier directly). This strategy effectively defers the question of whether a Name should be treated as a Primary until more context can be examined.
The second unusual feature avoids a potential grammatical ambiguity in the expression "new int[3][3]" which in Java always means a single creation of a multidimensional array, but which, without appropriate grammatical finesse, might also be interpreted as meaning the same as "(new int[3])[3]".
This ambiguity is eliminated by splitting the expected definition of Primary into Primary and PrimaryNoNewArray. (This may be compared to the splitting of Statement into Statement and StatementNoShortIf (§14.5) to avoid the "dangling else" problem.)
15.8.1. Lexical Literals
A literal (§3.10) denotes a fixed, unchanging value.
The following production from §3.10 is shown here for convenience:
Literal:
IntegerLiteral
FloatingPointLiteral
BooleanLiteral
CharacterLiteral
StringLiteral
TextBlock
NullLiteral
The type of a literal is determined as follows:
The type of an integer literal (§3.10.1) that ends with L or l (ell) is long (§4.2.1).
The type of any other integer literal is int (§4.2.1).
The type of a floating-point literal (§3.10.2) that ends with F or f is float (§4.2.3).
The type of any other floating-point literal is double (§4.2.3).
The type of a boolean literal (§3.10.3) is boolean (§4.2.5).
The type of a character literal (§3.10.4) is char (§4.2.1).
The type of a string literal (§3.10.5) or a text block (§3.10.6) is String (§4.3.3).
The type of the null literal null (§3.10.8) is the null type (§4.1); its value is the null reference.
Evaluation of a lexical literal always completes normally.
15.8.2. Class Literals
A class literal is an expression consisting of the name of a class, interface, array type, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
ClassLiteral:
TypeName {[ ]} . class
NumericType {[ ]} . class
boolean {[ ]} . class
void . class
The TypeName must denote a class or interface that is accessible (§6.6). It is a compile-time error if the TypeName denotes a class or interface that is not accessible, or denotes a type variable.
The type of C.class, where C is the name of a class, interface, or array type (§4.3), is Class<C>.
The type of p.class, where p is the name of a primitive type (§4.2), is Class<B>, where B is the type of an expression of type p after boxing conversion (§5.1.7).
The type of void.class (§8.4.5) is Class<Void>.
A class literal evaluates to the Class object for the named class, interface, array type, or primitive type (or for void), as defined by the defining class loader (§12.2) of the class of the current instance.
15.8.3. this
The keyword this may be used as an expression in the following contexts:
in the body of an instance method of a class (§8.4.3.2)
in the body of a constructor of a class (§8.8.7)
in an instance initializer of a class (§8.6)
in the initializer of an instance variable of a class (§8.3.2)
in the body of an instance method of an interface, that is, a default method or a non-static private interface method (§9.4)
When used as an expression, the keyword this denotes a value that is a reference either to the object for which the instance method was invoked (§15.12), or to the object being constructed. The value denoted by this in a lambda body (§15.27.2) is the same as the value denoted by this in the surrounding context.
The keyword this is also used in explicit constructor invocation statements (§8.8.7.1), and to denote the receiver parameter of a method or constructor (§8.4).
It is a compile-time error if a this expression occurs in a static context (§8.1.3).
Let C be the innermost enclosing class or interface declaration of a this expression. If C is generic, with type parameters F1,...,Fn, the type of this is C<F1,...,Fn>. Otherwise, the type of this is C.
At run time, the class of the actual object referred to may be C or a subclass of C (§8.1.5.
Example 15.8.3-1. The this Expression
class IntVector {
int[] v;
boolean equals(IntVector other) {
if (this == other)
return true;
if (v.length != other.v.length)
return false;
for (int i = 0; i < v.length; i++) {
if (v[i] != other.v[i]) return false;
}
return true;
}
}
Here, the class IntVector implements a method equals, which compares two vectors. If the other vector is the same vector object as the one for which the equals method was invoked, then the check can skip the length and value comparisons. The equals method implements this check by comparing the reference to the other object to this.
15.8.4. Qualified this
Any lexically enclosing instance (§8.1.3) can be referred to by explicitly qualifying the keyword this.
Let n be an integer such that TypeName denotes the n'th lexically enclosing class or interface declaration of the class or interface whose declaration immediately encloses the qualified this expression.
The value of a qualified this expression TypeName.this is the n'th lexically enclosing instance of this.
If TypeName denotes a generic class, with type parameters F1,...,Fn, the type of the qualified this expression is TypeName<F1,...,Fn>. Otherwise, the type of the qualified this expression is TypeName.
It is a compile-time error if a qualified this expression occurs in a static context (§8.1.3).
It is a compile-time error if the class or interface whose declaration immediately encloses a qualified this expression is not an inner class of TypeName or TypeName itself.
15.8.5. Parenthesized Expressions
A parenthesized expression is a primary expression whose type is the type of the contained expression and whose value at run time is the value of the contained expression. If the contained expression denotes a variable then the parenthesized expression also denotes that variable.
The use of parentheses affects only the order of evaluation, except for a corner case whereby (-2147483648) and (-9223372036854775808L) are legal but -(2147483648) and -(9223372036854775808L) are illegal.
This is because the decimal literals 2147483648 and 9223372036854775808L are allowed only as an operand of the unary minus operator (§3.10.1).
In particular, the presence or absence of parentheses around an expression does not affect whether a variable is definitely assigned, definitely assigned when true, definitely assigned when false, definitely unassigned, definitely unassigned when true, or definitely unassigned when false (§16 (Definite Assignment)).
If a parenthesized expression appears in a context of a particular kind with target type T (§5 (Conversions and Contexts)), its contained expression similarly appears in a context of the same kind with target type T.
If the contained expression is a poly expression (§15.2), the parenthesized expression is also a poly expression. Otherwise, it is a standalone expression.
A poly parenthesized expression is compatible with a target type T if its contained expression is compatible with T.
15.9. Class Instance Creation Expressions
A class instance creation expression is used to create new objects that are instances of classes.
ClassInstanceCreationExpression:
UnqualifiedClassInstanceCreationExpression
ExpressionName . UnqualifiedClassInstanceCreationExpression
Primary . UnqualifiedClassInstanceCreationExpression
UnqualifiedClassInstanceCreationExpression:
new [TypeArguments] ClassOrInterfaceTypeToInstantiate ( [ArgumentList] ) [ClassBody]
ClassOrInterfaceTypeToInstantiate:
{Annotation} Identifier {. {Annotation} Identifier} [TypeArgumentsOrDiamond]
TypeArgumentsOrDiamond:
TypeArguments
<>
The following production from §15.12 is shown here for convenience:
ArgumentList:
Expression {, Expression}
A class instance creation expression specifies a class to be instantiated, possibly followed by type arguments (§4.5.1) or a diamond (<>) if the class being instantiated is generic (§8.1.2), followed by (a possibly empty) list of actual value arguments to the constructor.
If the type argument list to the class is empty — the diamond form <> — the type arguments of the class are inferred. It is legal, though strongly discouraged as a matter of style, to have white space between the "<" and ">" of a diamond.
If the constructor is generic (§8.8.4), the type arguments to the constructor may similarly either be inferred or passed explicitly. If passed explicitly, the type arguments to the constructor immediately follow the keyword new.
It is a compile-time error if a class instance creation expression provides type arguments to a constructor but uses the diamond form for type arguments to the class.
This rule is introduced because inference of a generic class's type arguments may influence the constraints on a generic constructor's type arguments.
If TypeArguments is present immediately after new, or immediately before (, then it is a compile-time error if any of the type arguments are wildcards (§4.5.1).
The exception types that a class instance creation expression can throw are specified in §11.2.1.
Class instance creation expressions have two forms:
Unqualified class instance creation expressions begin with the keyword new.
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 (§7.6), member (§8.5, §9.5), local (§14.3), or anonymous class (§15.9.5).
Qualified class instance creation expressions begin with a Primary expression or an ExpressionName.
A qualified class instance creation expression enables the creation of instances of inner member classes and their anonymous subclasses.
Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (§15.9.5) and creates an instance of it.
A class instance creation expression is a poly expression (§15.2) if it uses the diamond form for type arguments to the class, and it appears in an assignment context or an invocation context (§5.2, §5.3). Otherwise, it is a standalone expression.
We say that a class is instantiated when an instance of the class is created by a class instance creation expression. Class instantiation involves determining the class to be instantiated (§15.9.1), the enclosing instances (if any) of the newly created instance (§15.9.2), and the constructor to be invoked to create the new instance (§15.9.3).
15.9.1. Determining the Class being Instantiated
If ClassOrInterfaceTypeToInstantiate ends with TypeArguments (rather than <>), then ClassOrInterfaceTypeToInstantiate must denote a well-formed parameterized type (§4.5), or a compile-time error occurs.
If ClassOrInterfaceTypeToInstantiate ends with <>, but the class or interface denoted by the Identifier in ClassOrInterfaceTypeToInstantiate is not generic, then a compile-time error occurs.
If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:
If the class instance creation expression is unqualified, then:
The Identifier in ClassOrInterfaceTypeToInstantiate must denote either a class that is accessible, freely extensible (§8.1.1.2), and not an enum class, or an interface that is accessible and freely extensible (§9.1.1.4). Otherwise, a compile-time error occurs.
If the Identifier in ClassOrInterfaceTypeToInstantiate denotes a class, C, then an anonymous direct subclass of C is declared. If TypeArguments is present, then C has type arguments given by TypeArguments; if <> is present, then C will have its type arguments inferred in §15.9.3; otherwise, C has no type arguments. The body of the subclass is the ClassBody given in the class instance creation expression. The class being instantiated is the anonymous subclass.
If the Identifier in ClassOrInterfaceTypeToInstantiate denotes an interface, I, then an anonymous direct subclass of Object that implements I is declared. If TypeArguments is present, then I has type arguments given by TypeArguments; if <> is present, then I will have its type arguments inferred in §15.9.3; otherwise, I has no type arguments. The body of the subclass is the ClassBody given in the class instance creation expression. The class being instantiated is the anonymous subclass.
If the class instance creation expression is qualified, then:
The Identifier in ClassOrInterfaceTypeToInstantiate must unambiguously denote an inner class that is accessible, freely extensible, not an enum class, and a member of the compile-time type of the Primary expression or the ExpressionName. Otherwise, a compile-time error occurs.
Let the Identifier in ClassOrInterfaceTypeToInstantiate denote a class, C. An anonymous direct subclass of C is declared. If TypeArguments is present, then C has type arguments given by TypeArguments; if <> is present, then C will have its type arguments inferred in §15.9.3; otherwise, C has no type arguments. The body of the subclass is the ClassBody given in the class instance creation expression. The class being instantiated is the anonymous subclass.
If a class instance creation expression does not declare an anonymous class, then:
If the class instance creation expression is unqualified, then:
The Identifier in ClassOrInterfaceTypeToInstantiate must denote a class that is accessible, non-abstract, and not an enum class. Otherwise, a compile-time error occurs.
The class being instantiated is specified by the Identifier in ClassOrInterfaceTypeToInstantiate. If TypeArguments is present, then the class has type arguments given by TypeArguments; if <> is present, then the class will have its type arguments inferred in §15.9.3; otherwise, the class has no type arguments.
If the class instance creation expression is qualified, then:
The ClassOrInterfaceTypeToInstantiate must unambiguously denote an inner class that is accessible, non-abstract, not an enum class, and a member of the compile-time type of the Primary expression or the ExpressionName.
The class being instantiated is specified by the Identifier in ClassOrInterfaceTypeToInstantiate. If TypeArguments is present, then the class has type arguments given by TypeArguments; if <> is present, then the class will have its type arguments inferred in §15.9.3; otherwise, the class has no type arguments.
15.9.2. Determining Enclosing Instances
Let C be the class being instantiated, and let i be the instance being created. If C is an inner class, then i may have an immediately enclosing instance (§8.1.3), determined as follows:
If C is an anonymous class, then:
If the class instance creation expression occurs in a static context, then i has no immediately enclosing instance.
Otherwise, the immediately enclosing instance of i is this.
If C is an inner local class, then:
If C occurs in a static context, then i has no immediately enclosing instance.
Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, let O be the immediately enclosing class or interface declaration of C, and let U be the immediately enclosing class or interface declaration of the class instance creation expression.
If U is not an inner class of O or O itself, then a compile-time error occurs.
Let n be an integer such that O is the n'th lexically enclosing class or interface declaration of U.
The immediately enclosing instance of i is the n'th lexically enclosing instance of this.
If C is an inner member class, then:
If the class instance creation expression is unqualified, then:
If the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, if C is not a member of any class whose declaration lexically encloses the class instance creation expression, then a compile-time error occurs.
Otherwise, let O be the innermost enclosing class declaration of which C is a member, and let U be the immediately enclosing class or interface declaration of the class instance creation expression.
If U is not an inner class of O or O itself, then a compile-time error occurs.
Let n be an integer such that O is the n'th lexically enclosing class or interface declaration of U
The immediately enclosing instance of i is the n'th lexically enclosing instance of this.
If the class instance creation expression is qualified, then the immediately enclosing instance of i is the object that is the value of the Primary expression or the ExpressionName.
If C is an anonymous class, and its direct superclass S is an inner class, then i may have an immediately enclosing instance with respect to S, determined as follows:
If S is an inner local class, then:
If S occurs in a static context, then i has no immediately enclosing instance with respect to S.
Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, let O be the immediately enclosing class or interface declaration of S, and let U be the immediately enclosing class or interface declaration of the class instance creation expression.
If U is not an inner class of O or O itself, then a compile-time error occurs.
Let n be an integer such that O is the n'th lexically enclosing class or interface declaration of U.
The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of this.
If S is an inner member class, then:
If the class instance creation expression is unqualified, then:
If the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, if S is not a member of any class whose declaration encloses the class instance creation expression, then a compile-time error occurs.
Otherwise, let O be the innermost enclosing class declaration of which S is a member, and let U be the immediately enclosing class or interface declaration of the class instance creation expression.
If U is not an inner class of O or O itself, then a compile-time error occurs.
Let n be an integer such that O is the n'th lexically enclosing class or interface declaration of U.
The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of this.
Otherwise, a compile-time error occurs.
If the class instance creation expression is qualified, then the immediately enclosing instance of i with respect to S is the object that is the value of the Primary expression or the ExpressionName.
15.9.3. Choosing the Constructor and its Arguments
Let C be the class being instantiated. To create an instance of C, i, a constructor of C is chosen at compile time by the following rules.
First, the actual arguments to the constructor invocation are determined:
If C is an anonymous class with direct superclass S, then:
If S is not an inner class, or if S is a local class that occurs in a static context, then the arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the expression.
Otherwise, the first argument to the constructor is the immediately enclosing instance of i with respect to S (§15.9.2), and the subsequent arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the class instance creation expression.
If C is a local class or a private inner member class, then the arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the class instance creation expression.
If C is a non-private inner member class, then the first argument to the constructor is the immediately enclosing instance of i (§8.8.1, §15.9.2), and the subsequent arguments to its constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the class instance creation expression.
Otherwise, the arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the expression.
Second, a constructor of C and corresponding throws clause and return type are determined:
If the class instance creation expression does not use <>, then:
If C is not an anonymous class, then:
Let T be the type denoted by C followed by any class type arguments in the expression. The process specified in §15.12.2, modified to handle constructors, is used to choose one of the constructors of T and determine its throws clause.
If there is no unique most-specific constructor in T that is both applicable and accessible (§6.6), then a compile-time error occurs (as in method invocations).
Otherwise, the return type corresponding to the chosen constructor is T.
If C is an anonymous class, then:
The process specified in §15.12.2, modified to handle constructors, is used to choose one of the constructors of the direct superclass type of C and determine its throws clause.
If there is no unique most-specific constructor in the direct superclass type of C that is both applicable and accessible, then a compile-time error occurs (as in method invocations).
Otherwise, C's anonymous constructor is chosen as the constructor of C (§15.9.5.1). Its body consists of an explicit constructor invocation (§8.8.7.1) of the constructor chosen in the direct superclass type of C.
The throws clause of the chosen constructor includes the exceptions in the throws clause of the constructor chosen in the direct superclass type of C.
The return type corresponding to the chosen constructor is the anonymous class type.
If the class instance creation expression uses <>, then:
If C is not an anonymous class, let D be the same as C. If C is an anonymous class, let D be the superclass or superinterface of C named by the class instance creation expression.
If D is a class, let c1, ..., cn be the constructors of class D. If D is an interface, let c1, ..., cn be a singleton list (n = 1) containing the zero-argument constructor of the class Object.
A list of methods m1, ..., mn is defined for the purpose of overload resolution and type argument inference. For all j (1 ≤ j ≤ n), mj is defined in terms of cj as follows:
A substitution θj is first defined to instantiate the types in cj.
Let F1, ..., Fp be the type parameters of D, and let G1, ..., Gq be the type parameters (if any) of cj. Let X1, ..., Xp and Y1, ..., Yq be type variables with distinct names that are not in scope in the body of D.
θj is [F1:=X1, ..., Fp:=Xp, G1:=Y1, ..., Gq:=Yq].
The type parameters of mj are X1, ..., Xp, Y1, ..., Yq. The bound of each type parameter, if any, is θj applied to the corresponding type parameter bound in D or cj.
The return type of mj is θj applied to D<F1, ..., Fp>.
The (possibly empty) list of argument types of mj is θj applied to the argument types of cj.
The (possibly empty) list of thrown types of mj is θj applied to the thrown types of cj.
The modifiers of mj are those of cj.
The name of mj is #m, an automatically generated name that is distinct from all constructor and method names in D and is shared by m1, ..., mn.
The body of mj is irrelevant.
To choose a constructor, we temporarily consider m1, ..., mn to be members of D. One of m1, ..., mn is chosen, as determined by the class instance creation expression's argument expressions, using the process specified in §15.12.2.
If there is no unique most specific method that is both applicable and accessible, then a compile-time error occurs.
Otherwise, where mj is the chosen method:
If C is not an anonymous class, then cj is chosen as the constructor of C.
The throws clause of the chosen constructor is the same as the throws clause determined for mj.
The return type corresponding to the chosen constructor is the return type determined for mj (§15.12.2.6).
If C is an anonymous class, then C's anonymous constructor is chosen as the constructor of C. Its body consists of an explicit constructor invocation (§8.8.7.1) of cj.
The throws clause of the chosen constructor includes the exceptions in the throws clause determined for mj.
The return type corresponding to the chosen constructor is the anonymous class type.
If the class instance creation expression is a poly expression, then its compatibility with a target type is as determined by §18.5.2.1, using mj as the selected method m.
Testing for compatibility with a target type may occur multiple times before making a final determination of the class instance creation expression's target type and the return type corresponding to the chosen constructor. For example, an enclosing method invocation expression may require testing the class instance creation expression for compatibility with different methods' formal parameter types.
If C is an anonymous class, then its direct superclass type or direct superinterface type is the return type determined for mj (§15.12.2.6).
It is a compile-time error if the direct superclass type or direct superinterface type, or any subexpression therein ("subexpression" includes type arguments of parameterized types, bounds of wildcard type arguments, and element types of array types, but excludes bounds of type variables), has one of the following forms:
A type variable that was not declared as a type parameter (such as a type variable produced by capture conversion).