-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter-4.txt
1813 lines (1039 loc) · 99.4 KB
/
chapter-4.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 4. Types, Values, and Variables
Table of Contents
4.1. The Kinds of Types and Values
4.2. Primitive Types and Values
4.2.1. Integral Types and Values
4.2.2. Integer Operations
4.2.3. Floating-Point Types and Values
4.2.4. Floating-Point Operations
4.2.5. The boolean Type and boolean Values
4.3. Reference Types and Values
4.3.1. Objects
4.3.2. The Class Object
4.3.3. The Class String
4.3.4. When Reference Types Are the Same
4.4. Type Variables
4.5. Parameterized Types
4.5.1. Type Arguments of Parameterized Types
4.5.2. Members and Constructors of Parameterized Types
4.6. Type Erasure
4.7. Reifiable Types
4.8. Raw Types
4.9. Intersection Types
4.10. Subtyping
4.10.1. Subtyping among Primitive Types
4.10.2. Subtyping among Class and Interface Types
4.10.3. Subtyping among Array Types
4.10.4. Least Upper Bound
4.10.5. Type Projections
4.11. Where Types Are Used
4.12. Variables
4.12.1. Variables of Primitive Type
4.12.2. Variables of Reference Type
4.12.3. Kinds of Variables
4.12.4. final Variables
4.12.5. Initial Values of Variables
4.12.6. Types, Classes, and Interfaces
The Java programming language is a statically typed language, which means that every variable and every expression has a type that is known at compile time.
The Java programming language is also a strongly typed language, because types limit the values that a variable (§4.12) can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong static typing helps detect errors at compile time.
The types of the Java programming language are divided into two kinds: primitive types and reference types. The primitive types (§4.2) are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types (§4.3) are class types, interface types, and array types. There is also a special null type. An object (§4.3.1) is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object (§4.3.2). String literals are represented by String objects (§4.3.3).
4.1. The Kinds of Types and Values
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
Type:
PrimitiveType
ReferenceType
There is also a special null type, the type of the expression null (§3.10.8, §15.8.1), which has no name.
Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.
The null reference is the only possible value of an expression of null type.
The null reference can always be assigned or cast to any reference type (§5.2, §5.3, §5.5).
In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.
4.2. Primitive Types and Values
A primitive type is predefined by the Java programming language and named by its reserved keyword (§3.9):
PrimitiveType:
{Annotation} NumericType
{Annotation} boolean
NumericType:
IntegralType
FloatingPointType
IntegralType:
(one of)
byte short int long char
FloatingPointType:
(one of)
float double
Primitive values do not share state with other primitive values.
The numeric types are the integral types and the floating-point types.
The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).
The floating-point types are float, whose values exactly correspond to the 32-bit IEEE 754 binary32 floating-point numbers, and double, whose values exactly correspond to the 64-bit IEEE 754 binary64 floating-point numbers.
The boolean type has exactly two values: true and false.
4.2.1. Integral Types and Values
The values of the integral types are integers in the following ranges:
For byte, from -128 to 127, inclusive
For short, from -32768 to 32767, inclusive
For int, from -2147483648 to 2147483647, inclusive
For long, from -9223372036854775808 to 9223372036854775807, inclusive
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
4.2.2. Integer Operations
The Java programming language provides a number of operators that act on integral values:
The comparison operators, which result in a value of type boolean:
The numerical comparison operators <, <=, >, and >= (§15.20.1)
The numerical equality operators == and != (§15.21.1)
The numerical operators, which result in a value of type int or long:
The unary plus and minus operators + and - (§15.15.3, §15.15.4)
The multiplicative operators *, /, and % (§15.17)
The additive operators + and - (§15.18)
The increment operator ++, both prefix (§15.15.1) and postfix (§15.14.2)
The decrement operator --, both prefix (§15.15.2) and postfix (§15.14.3)
The signed and unsigned shift operators <<, >>, and >>> (§15.19)
The bitwise complement operator ~ (§15.15.5)
The integer bitwise operators &, ^, and | (§15.22.1)
The conditional operator ? : (§15.25)
The cast operator (§15.16), which can convert from an integral value to a value of any specified numeric type
The string concatenation operator + (§15.18.1), which, when given a String operand and an integral operand, will convert the integral operand to a String (the decimal form of a byte, short, int, or long operand, or the character of a char operand), and then produce a newly created String that is the concatenation of the two strings
Other useful constructors, methods, and constants are predefined in the classes Byte, Short, Integer, Long, and Character.
If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).
Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.
The integer operators do not indicate overflow or underflow in any way.
Any value of any integral type may be cast to or from any numeric type. There are no casts between integral types and the type boolean.
See §4.2.5 for an idiom to convert integer expressions to boolean.
An integer operator can throw an exception (§11 (Exceptions)) for the following reasons:
Any integer operator can throw a NullPointerException if unboxing conversion (§5.1.8) of a null reference is required.
The integer divide operator / (§15.17.2) and the integer remainder operator % (§15.17.3) can throw an ArithmeticException if the right-hand operand is zero.
The increment and decrement operators ++ (§15.14.2, §15.15.1) and -- (§15.14.3, §15.15.2) can throw an OutOfMemoryError if boxing conversion (§5.1.7) is required and there is not sufficient memory available to perform the conversion.
Example 4.2.2-1. Integer Operations
class Test {
public static void main(String[] args) {
int i = 1000000;
System.out.println(i * i);
long l = i;
System.out.println(l * l);
System.out.println(20296 / (l - i));
}
}
This program produces the output:
-727379968
1000000000000
and then encounters an ArithmeticException in the division by l - i, because l - i is zero. The first multiplication is performed in 32-bit precision, whereas the second multiplication is a long multiplication. The value -727379968 is the decimal value of the low 32 bits of the mathematical result, 1000000000000, which is a value too large for type int.
4.2.3. Floating-Point Types and Values
The floating-point types are float and double, which are conceptually associated with the 32-bit binary32 and 64-bit binary64 floating-point formats for IEEE 754 values and operations, as specified in the IEEE 754 Standard (§1.7).
In Java SE 15 and later, the Java programming language uses the 2019 version of the IEEE 754 Standard. Prior to Java SE 15, the Java programming language used the 1985 version of the IEEE 754 Standard, where the binary32 format was known as the single format and the binary64 format was known as the double format.
IEEE 754 includes not only positive and negative numbers that consist of a sign and magnitude, but also positive and negative zeros, positive and negative infinities, and special Not-a-Number values (hereafter abbreviated NaN). A NaN value is used to represent the result of certain invalid operations such as dividing zero by zero. NaN constants of both float and double type are predefined as Float.NaN and Double.NaN.
The finite nonzero values of a floating-point type can all be expressed in the form s ⋅ m ⋅ 2(e - N + 1), where:
s is +1 or -1,
m is a positive integer less than 2N,
e is an integer between Emin = -(2K-1-2) and Emax = 2K-1-1, inclusive, and
N and K are parameters that depend on the type.
Some values can be represented in this form in more than one way. For example, supposing that a value v of a floating-point type might be represented in this form using certain values for s, m, and e, then if it happened that m were even and e were less than 2K-1, one could halve m and increase e by 1 to produce a second representation for the same value v.
A representation in this form is called normalized if m ≥ 2N-1; otherwise the representation is said to be subnormal. If a value of a floating-point type cannot be represented in such a way that m ≥ 2N-1, then the value is said to be a subnormal value, because its magnitude is below the magnitude of the smallest normalized value.
The constraints on the parameters N and K (and on the derived parameters Emin and Emax) for float and double are summarized in Table 4.2.3-A.
Table 4.2.3-A. Floating-point parameters
Parameter float double
N 24 53
K 8 11
Emax +127 +1023
Emin -126 -1022
Except for NaN, floating-point values are ordered. Arranged from smallest to largest, they are negative infinity, negative finite nonzero values, negative and positive zero, positive finite nonzero values, and positive infinity.
IEEE 754 allows multiple distinct NaN values for each of its binary32 and binary64 floating-point formats. However, the Java SE Platform generally treats NaN values of a given floating-point type as though collapsed into a single canonical value, and hence this specification normally refers to an arbitrary NaN as though to a canonical value.
Under IEEE 754, a floating-point operation with non-NaN arguments may generate a NaN result. IEEE 754 specifies a set of NaN bit patterns, but does not mandate which particular NaN bit pattern is used to represent a NaN result; this is left to the hardware architecture. A programmer can create NaNs with different bit patterns to encode, for example, retrospective diagnostic information. These NaN values can be created with the Float.intBitsToFloat and Double.longBitsToDouble methods for float and double, respectively. Conversely, to inspect the bit patterns of NaN values, the Float.floatToRawIntBits and Double.doubleToRawLongBits methods can be used for float and double, respectively.
Positive zero and negative zero compare equal, so the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. Other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity.
NaN is unordered, so:
The numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1).
In particular, (x<y) == !(x>=y) will be false if x or y is NaN.
The equality operator == returns false if either operand is NaN.
The inequality operator != returns true if either operand is NaN (§15.21.1).
In particular, x!=x is true if and only if x is NaN.
4.2.4. Floating-Point Operations
The Java programming language provides a number of operators that act on floating-point values:
The comparison operators, which result in a value of type boolean:
The numerical comparison operators <, <=, >, and >= (§15.20.1)
The numerical equality operators == and != (§15.21.1)
The numerical operators, which result in a value of type float or double:
The unary plus and minus operators + and - (§15.15.3, §15.15.4)
The multiplicative operators *, /, and % (§15.17)
The additive operators + and - (§15.18.2)
The increment operator ++, both prefix (§15.15.1) and postfix (§15.14.2)
The decrement operator --, both prefix (§15.15.2) and postfix (§15.14.3)
The conditional operator ? : (§15.25)
The cast operator (§15.16), which can convert from a floating-point value to a value of any specified numeric type
The string concatenation operator + (§15.18.1), which, when given a String operand and a floating-point operand, will convert the floating-point operand to a String representing its value in decimal form (without information loss), and then produce a newly created String by concatenating the two strings
Other useful constructors, methods, and constants are predefined in the classes Float, Double, and Math.
If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other operand is integral.
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).
Otherwise, at least one of the operands is of type float; the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. If the other operand is not a float, it is first widened to type float by numeric promotion.
Floating-point arithmetic is carried out in accordance with the rules of the IEEE 754 Standard, including for overflow and underflow (§15.4), with the exception of the remainder operator % (§15.17.3).
Any value of a floating-point type may be cast to or from any numeric type. There are no casts between floating-point types and the type boolean.
See §4.2.5 for an idiom to convert floating-point expressions to boolean.
A floating-point operator can throw an exception (§11 (Exceptions)) for the following reasons:
Any floating-point operator can throw a NullPointerException if unboxing conversion (§5.1.8) of a null reference is required.
The increment and decrement operators ++ (§15.14.2, §15.15.1) and -- (§15.14.3, §15.15.2) can throw an OutOfMemoryError if boxing conversion (§5.1.7) is required and there is not sufficient memory available to perform the conversion.
Example 4.2.4-1. Floating-point Operations
class Test {
public static void main(String[] args) {
// An example of overflow:
double d = 1e308;
System.out.print("overflow produces infinity: ");
System.out.println(d + "*10==" + d*10);
// An example of gradual underflow:
d = 1e-305 * Math.PI;
System.out.print("gradual underflow: " + d + "\n ");
for (int i = 0; i < 4; i++)
System.out.print(" " + (d /= 100000));
System.out.println();
// An example of NaN:
System.out.print("0.0/0.0 is Not-a-Number: ");
d = 0.0/0.0;
System.out.println(d);
// An example of inexact results and rounding:
System.out.print("inexact results with float:");
for (int i = 0; i < 100; i++) {
float z = 1.0f / i;
if (z * i != 1.0f)
System.out.print(" " + i);
}
System.out.println();
// Another example of inexact results and rounding:
System.out.print("inexact results with double:");
for (int i = 0; i < 100; i++) {
double z = 1.0 / i;
if (z * i != 1.0)
System.out.print(" " + i);
}
System.out.println();
// An example of cast to integer rounding:
System.out.print("cast to int rounds toward 0: ");
d = 12345.6;
System.out.println((int)d + " " + (int)(-d));
}
}
This program produces the output:
overflow produces infinity: 1.0E308*10==Infinity
gradual underflow: 3.141592653589793E-305
3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0
0.0/0.0 is Not-a-Number: NaN
inexact results with float: 0 41 47 55 61 82 83 94 97
inexact results with double: 0 49 98
cast to int rounds toward 0: 12345 -12345
This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision.
The results when i is 0 involve division by zero, so that z becomes positive infinity, and z * 0 is NaN, which is not equal to 1.0.
4.2.5. The boolean Type and boolean Values
The boolean type represents a logical quantity with two possible values, indicated by the literals true and false (§3.10.3).
The boolean operators are:
The relational operators == and != (§15.21.2)
The logical complement operator ! (§15.15.6)
The logical operators &, ^, and | (§15.22.2)
The conditional-and and conditional-or operators && (§15.23) and || (§15.24)
The conditional operator ? : (§15.25)
The string concatenation operator + (§15.18.1), which, when given a String operand and a boolean operand, will convert the boolean operand to a String (either "true" or "false"), and then produce a newly created String that is the concatenation of the two strings
Boolean expressions determine the control flow in several kinds of statements:
The if statement (§14.9)
The while statement (§14.12)
The do statement (§14.13)
The for statement (§14.14)
A boolean expression also determines which subexpression is evaluated in the conditional ? : operator (§15.25).
Only boolean and Boolean expressions can be used in control flow statements and as the first operand of the conditional operator ? :.
An integer or floating-point expression x can be converted to a boolean value, following the C language convention that any nonzero value is true, by the expression x!=0.
An object reference obj can be converted to a boolean value, following the C language convention that any reference other than null is true, by the expression obj!=null.
A boolean value can be converted to a String by string conversion (§5.4).
A boolean value may be cast to type boolean, Boolean, or Object (§5.5). No other casts on type boolean are allowed.
4.3. Reference Types and Values
There are four kinds of reference types: class types (§8.1), interface types (§9.1), type variables (§4.4), and array types (§10.1).
ReferenceType:
ClassOrInterfaceType
TypeVariable
ArrayType
ClassOrInterfaceType:
ClassType
InterfaceType
ClassType:
{Annotation} TypeIdentifier [TypeArguments]
PackageName . {Annotation} TypeIdentifier [TypeArguments]
ClassOrInterfaceType . {Annotation} TypeIdentifier [TypeArguments]
InterfaceType:
ClassType
TypeVariable:
{Annotation} TypeIdentifier
ArrayType:
PrimitiveType Dims
ClassOrInterfaceType Dims
TypeVariable Dims
Dims:
{Annotation} [ ] {{Annotation} [ ]}
The sample code:
class Point { int[] metrics; }
interface Move { void move(int deltax, int deltay); }
declares a class type Point, an interface type Move, and uses an array type int[] (an array of int) to declare the field metrics of the class Point.
A class or interface type consists of an identifier or a dotted sequence of identifiers, where each identifier is optionally followed by type arguments (§4.5.1). If type arguments appear anywhere in a class or interface type, it is a parameterized type (§4.5).
Each identifier in a class or interface type is classified as a package name or a type name (§6.5.1). Identifiers which are classified as type names may be annotated. If a class or interface type has the form T.id (optionally followed by type arguments), then id must be the simple name of an accessible member type of T (§6.6, §8.5, §9.5), or a compile-time error occurs. The class or interface type denotes that member type.
4.3.1. Objects
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
A class instance is explicitly created by a class instance creation expression (§15.9).
An array is explicitly created by an array creation expression (§15.10.1).
Other expressions may implicitly create a class instance (§12.5) or an array (§10.6).
Example 4.3.1-1. Object Creation
class Point {
int x, y;
Point() { System.out.println("default"); }
Point(int x, int y) { this.x = x; this.y = y; }
/* A Point instance is explicitly created at
class initialization time: */
static Point origin = new Point(0,0);
/* A String can be implicitly created
by a + operator: */
public String toString() { return "(" + x + "," + y + ")"; }
}
class Test {
public static void main(String[] args) {
/* A Point is explicitly created
using newInstance: */
Point p = null;
try {
p = (Point)Class.forName("Point").newInstance();
} catch (Exception e) {
System.out.println(e);
}
/* An array is implicitly created
by an array initializer: */
Point[] a = { new Point(0,0), new Point(1,1) };
/* Strings are implicitly created
by + operators: */
System.out.println("p: " + p);
System.out.println("a: { " + a[0] + ", " + a[1] + " }");
/* An array is explicitly created
by an array creation expression: */
String[] sa = new String[2];
sa[0] = "he"; sa[1] = "llo";
System.out.println(sa[0] + sa[1]);
}
}
This program produces the output:
default
p: (0,0)
a: { (0,0), (1,1) }
hello
The operators on references to objects are:
Field access, using either a qualified name (§6.6) or a field access expression (§15.11)
Method invocation (§15.12)
The cast operator (§5.5, §15.16)
The string concatenation operator + (§15.18.1), which, when given a String operand and a reference, will convert the reference to a String by invoking the toString method of the referenced object (using "null" if either the reference or the result of toString is a null reference), and then will produce a newly created String that is the concatenation of the two strings
The instanceof operator (§15.20.2)
The reference equality operators == and != (§15.21.3)
The conditional operator ? : (§15.25).
There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.
Example 4.3.1-2. Primitive and Reference Identity
class Value { int val; }
class Test {
public static void main(String[] args) {
int i1 = 3;
int i2 = i1;
i2 = 4;
System.out.print("i1==" + i1);
System.out.println(" but i2==" + i2);
Value v1 = new Value();
v1.val = 5;
Value v2 = v1;
v2.val = 6;
System.out.print("v1.val==" + v1.val);
System.out.println(" and v2.val==" + v2.val);
}
}
This program produces the output:
i1==3 but i2==4
v1.val==6 and v2.val==6
because v1.val and v2.val reference the same instance variable (§4.12.3) in the one Value object created by the only new expression, while i1 and i2 are different variables.
Each object is associated with a monitor (§17.1), which is used by synchronized methods (§8.4.3) and the synchronized statement (§14.19) to provide control over concurrent access to state by multiple threads (§17 (Threads and Locks)).
4.3.2. The Class Object
The class Object is a superclass (§8.1.4) of all other classes.
All class and array types inherit (§8.4.8) the methods of class Object, which are summarized as follows:
The method clone is used to make a duplicate of an object.
The method equals defines a notion of object equality, which is based on value, not reference, comparison.
The method finalize is run just before an object is destroyed (§12.6).
The method getClass returns the Class object that represents the class of the object.
A Class object exists for each reference type. It can be used, for example, to discover the fully qualified name of a class, its members, its immediate superclass, and any interfaces that it implements.
The type of a method invocation expression of getClass is Class<? extends |T|>, where T is the class or interface that was searched for getClass (§15.12.1) and |T| denotes the erasure of T (§4.6).
A class method that is declared synchronized (§8.4.3.6) synchronizes on the monitor associated with the Class object of the class.
The method hashCode is very useful, together with the method equals, in hashtables such as java.util.HashMap.
The methods wait, notify, and notifyAll are used in concurrent programming using threads (§17.2).
The method toString returns a String representation of the object.
4.3.3. The Class String
Instances of class String represent sequences of Unicode code points.
A String object has a constant (unchanging) value.
String literals (§3.10.5) and text blocks (§3.10.6) are references to instances of class String.
The string concatenation operator + (§15.18.1) implicitly creates a new String object when the result is not a constant expression (§15.29).
4.3.4. When Reference Types Are the Same
Two reference types are the same compile-time type if they are declared in compilation units associated with the same module (§7.3), and they have the same binary name (§13.1), and their type arguments, if any, are the same, applying this definition recursively.
When two reference types are the same, they are sometimes said to be the same class or the same interface.
At run time, several reference types with the same binary name may be loaded simultaneously by different class loaders. These types may or may not represent the same type declaration. Even if two such types do represent the same type declaration, they are considered distinct.
Two reference types are the same run-time type if:
They are both class or both interface types, are defined by the same class loader, and have the same binary name (§13.1), in which case they are sometimes said to be the same run-time class or the same run-time interface.
They are both array types, and their component types are the same run-time type (§10 (Arrays)).
4.4. Type Variables
A type variable is an unqualified identifier used as a type in class, interface, method, and constructor bodies.
A type variable is introduced by the declaration of a type parameter of a generic class, interface, method, or constructor (§8.1.2, §9.1.2, §8.4.4, §8.8.4).
TypeParameter:
{TypeParameterModifier} TypeIdentifier [TypeBound]
TypeParameterModifier:
Annotation
TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}
AdditionalBound:
& InterfaceType
The scope of a type variable declared as a type parameter is specified in §6.3.
Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:
a single type variable T, or
a class or interface type T possibly followed by interface types I1 & ... & In.
It is a compile-time error if any of the types I1, ..., In is a class type or type variable.
The erasures (§4.6) of all constituent types of a bound must be pairwise different, or a compile-time error occurs.
A type variable must not at the same time be a subtype of two interface types which are different parameterizations of the same generic interface, or a compile-time error occurs.
The order of types in a bound is only significant in that the erasure of a type variable is determined by the first type in its bound, and that a class type or type variable may only appear in the first position.
The members of a type variable X with bound T & I1 & ... & In are the members of the intersection type (§4.9) T & I1 & ... & In appearing at the point where the type variable is declared.
Example 4.4-1. Members of a Type Variable
package TypeVarMembers;
class C {
public void mCPublic() {}
protected void mCProtected() {}
void mCPackage() {}
private void mCPrivate() {}
}
interface I {
void mI();
}
class CT extends C implements I {
public void mI() {}
}
class Test {
<T extends C & I> void test(T t) {
t.mI(); // OK
t.mCPublic(); // OK
t.mCProtected(); // OK
t.mCPackage(); // OK
t.mCPrivate(); // Compile-time error
}
}
The type variable T has the same members as the intersection type C & I, which in turn has the same members as the empty class CT, defined in the same scope with equivalent supertypes. The members of an interface are always public, and therefore always inherited (unless overridden). Hence mI is a member of CT and of T. Among the members of C, all but mCPrivate are inherited by CT, and are therefore members of both CT and T.
If C had been declared in a different package than T, then the call to mCPackage would give rise to a compile-time error, as that member would not be accessible at the point where T is declared.
4.5. Parameterized Types
A class or interface that is generic (§8.1.2, §9.1.2) defines a set of parameterized types.
A parameterized type is a class or interface type of the form C<T1,...,Tn>, where C is the name of a generic class or interface, and <T1,...,Tn> is a list of type arguments that denote a particular parameterization of the generic class or interface.
A generic class or interface has type parameters F1,...,Fn with corresponding bounds B1,...,Bn. Each type argument Ti of a parameterized type ranges over all types that are subtypes of all types listed in the corresponding bound. That is, for each bound type S in Bi, Ti is a subtype of S[F1:=T1,...,Fn:=Tn] (§4.10).
A parameterized type C<T1,...,Tn> is well-formed if all of the following are true:
C is the name of a generic class or interface.
The number of type arguments is the same as the number of type parameters in the generic declaration of C.
When subjected to capture conversion (§5.1.10) resulting in the type C<X1,...,Xn>, each type argument Xi is a subtype of S[F1:=X1,...,Fn:=Xn] for each bound type S in Bi.
It is a compile-time error if a parameterized type is not well-formed.
In this specification, whenever we speak of a class or interface type, we include parameterized types as well, unless explicitly excluded.
Two parameterized types are provably distinct if either of the following is true:
They are parameterizations of distinct generic type declarations.
Any of their type arguments are provably distinct.
Given the generic classes in the examples of §8.1.2, here are some well-formed parameterized types:
Seq<String>
Seq<Seq<String>>
Seq<String>.Zipper<Integer>
Pair<String,Integer>
Here are some incorrect parameterizations of those generic classes:
Seq<int> is illegal, as primitive types cannot be type arguments.
Pair<String> is illegal, as there are not enough type arguments.
Pair<String,String,String> is illegal, as there are too many type arguments.
A parameterized type may be a parameterization of a generic class or interface which is nested. For example, if a non-generic class C has a generic member class D with one type parameter, then C.D<Object> is a parameterized type. Meanwhile, if a generic class C with one type parameter has a non-generic member class D, then the member class type C<String>.D is a parameterized type, even though the class D is not generic.
4.5.1. Type Arguments of Parameterized Types
Type arguments may be either reference types or wildcards. Wildcards are useful in situations where only partial knowledge about the type parameter is required.
TypeArguments:
< TypeArgumentList >
TypeArgumentList:
TypeArgument {, TypeArgument}
TypeArgument:
ReferenceType
Wildcard
Wildcard:
{Annotation} ? [WildcardBounds]
WildcardBounds:
extends ReferenceType
super ReferenceType
Wildcards may be given explicit bounds, just like regular type variable declarations. An upper bound is signified by the following syntax, where B is the bound:
? extends B
Unlike ordinary type variables declared in a method signature, no type inference is required when using a wildcard. Consequently, it is permissible to declare lower bounds on a wildcard, using the following syntax, where B is a lower bound:
? super B
The wildcard ? extends Object is equivalent to the unbounded wildcard ?.
Two type arguments are provably distinct if one of the following is true:
Neither argument is a type variable or wildcard, and the two arguments are not the same type.
One type argument is a type variable or wildcard, with a bound (if a type variable) or an upper bound (if a wildcard, using capture conversion (§5.1.10), if necessary) of S; and the other type argument T is not a type variable or wildcard; and neither |S| <: |T| nor |T| <: |S| (§4.8, §4.10).
Each type argument is a type variable or wildcard, with upper bounds (from capture conversion, if necessary) of S and T; and neither |S| <: |T| nor |T| <: |S|.
A type argument T1 is said to contain another type argument T2, written T2 <= T1, if the set of types denoted by T2 is provably a subset of the set of types denoted by T1 under the reflexive and transitive closure of the following rules (where <: denotes subtyping (§4.10)):
? extends T <= ? extends S if T <: S
? extends T <= ?
? super T <= ? super S if S <: T
? super T <= ?
? super T <= ? extends Object
T <= T
T <= ? extends T
T <= ? super T
The relationship of wildcards to established type theory is an interesting one, which we briefly allude to here. Wildcards are a restricted form of existential types. Given a generic type declaration G<T extends B>, G<?> is roughly analogous to Some X <: B. G<X>.
Historically, wildcards are a direct descendant of the work by Atsushi Igarashi and Mirko Viroli. Readers interested in a more comprehensive discussion should refer to On Variance-Based Subtyping for Parametric Types by Atsushi Igarashi and Mirko Viroli, in the Proceedings of the 16th European Conference on Object Oriented Programming (ECOOP 2002). This work itself builds upon earlier work by Kresten Thorup and Mads Torgersen (Unifying Genericity, ECOOP 99), as well as a long tradition of work on declaration based variance that goes back to Pierre America's work on POOL (OOPSLA 89).
Wildcards differ in certain details from the constructs described in the aforementioned paper, in particular in the use of capture conversion (§5.1.10) rather than the close operation described by Igarashi and Viroli. For a formal account of wildcards, see Wild FJ by Mads Torgersen, Erik Ernst and Christian Plesner Hansen, in the 12th workshop on Foundations of Object Oriented Programming (FOOL 2005).
Example 4.5.1-1. Unbounded Wildcards
import java.util.ArrayList;
import java.util.Collection;
class Test {
static void printCollection(Collection<?> c) {
// a wildcard collection
for (Object o : c) {
System.out.println(o);
}
}
public static void main(String[] args) {
Collection<String> cs = new ArrayList<String>();
cs.add("hello");
cs.add("world");
printCollection(cs);
}
}
Note that using Collection<Object> as the type of the incoming parameter, c, would not be nearly as useful; the method could only be used with an argument expression that had type Collection<Object>, which would be quite rare. In contrast, the use of an unbounded wildcard allows any kind of collection to be passed as an argument.
Here is an example where the element type of an array is parameterized by a wildcard:
public Method getMethod(Class<?>[] parameterTypes) { ... }
Example 4.5.1-2. Bounded Wildcards
boolean addAll(Collection<? extends E> c)
Here, the method is declared within the interface Collection<E>, and is designed to add all the elements of its incoming argument to the collection upon which it is invoked. A natural tendency would be to use Collection<E> as the type of c, but this is unnecessarily restrictive. An alternative would be to declare the method itself to be generic:
<T> boolean addAll(Collection<T> c)
This version is sufficiently flexible, but note that the type parameter is used only once in the signature. This reflects the fact that the type parameter is not being used to express any kind of interdependency between the type(s) of the argument(s), the return type and/or throws type. In the absence of such interdependency, generic methods are considered bad style, and wildcards are preferred.
Reference(T referent, ReferenceQueue<? super T> queue)
Here, the referent can be inserted into any queue whose element type is a supertype of the type T of the referent; T is the lower bound for the wildcard.
4.5.2. Members and Constructors of Parameterized Types
Let C be a generic class or interface with type parameters A1,...,An, and let C<T1,...,Tn> be a parameterization of C where, for 1 ≤ i ≤ n, Ti is a type (rather than a wildcard). Then:
Let m be a member or constructor declaration in C, whose type as declared is T (§8.2, §8.8.6).
The type of m in C<T1,...,Tn> is T[A1:=T1,...,An:=Tn].
Let m be a member or constructor declaration in D, where D is a class extended by C or an interface implemented by C. Let D<U1,...,Uk> be the supertype (§4.10.2) of C<T1,...,Tn> that corresponds to D.
The type of m in C<T1,...,Tn> is the type of m in D<U1,...,Uk>.
If any of the type arguments in the parameterization of C are wildcards, then:
The types of the fields, methods, and constructors in C<T1,...,Tn> are the types of the fields, methods, and constructors in the capture conversion of C<T1,...,Tn> (§5.1.10).
Let D be a (possibly generic) class or interface declaration in C. Then the type of D in C<T1,...,Tn> is D where, if D is generic, all type arguments are unbounded wildcards.
This is of no consequence, as it is impossible to access a member of a parameterized type without performing capture conversion, and it is impossible to use a wildcard after the keyword new in a class instance creation expression (§15.9).
The sole exception to the previous paragraph is when a nested parameterized type is used as the expression in an instanceof operator (§15.20.2), where capture conversion is not applied.
A static member that is declared in a generic class or interface must be referred to using the name of the generic class or interface (§6.1, §6.5.5.2, §6.5.6.2), or a compile-time error occurs.
In other words, it is illegal to refer to a static member declared in a generic type declaration by using a parameterized type.
4.6. Type Erasure
Type erasure is a mapping from types (possibly including parameterized types and type variables) to types (that are never parameterized types or type variables). We write |T| for the erasure of type T. The erasure mapping is defined as follows:
The erasure of a parameterized type (§4.5) G<T1,...,Tn> is |G|.
The erasure of a nested type T.C is |T|.C.
The erasure of an array type T[] is |T|[].
The erasure of a type variable (§4.4) is the erasure of its leftmost bound.
The erasure of every other type is the type itself.
Type erasure also maps the signature (§8.4.2) of a constructor or method to a signature that has no parameterized types or type variables. The erasure of a constructor or method signature s is a signature consisting of the same name as s and the erasures of all the formal parameter types given in s.
The return type of a method (§8.4.5) and the type parameters of a generic method or constructor (§8.4.4, §8.8.4) also undergo erasure if the method or constructor's signature is erased.
The erasure of the signature of a generic method has no type parameters.
4.7. Reifiable Types
Because some type information is erased during compilation, not all types are available at run time. Types that are completely available at run time are known as reifiable types.
A type is reifiable if and only if one of the following holds:
It refers to a non-generic class or interface type declaration.
It is a parameterized type in which all type arguments are unbounded wildcards (§4.5.1).
It is a raw type (§4.8).
It is a primitive type (§4.2).
It is an array type (§10.1) whose element type is reifiable.
It is a nested type where, for each type T separated by a ".", T itself is reifiable.
For example, if a generic class X<T> has a generic member class Y<U>, then the type X<?>.Y<?> is reifiable because X<?> is reifiable and Y<?> is reifiable. The type X<?>.Y<Object> is not reifiable because Y<Object> is not reifiable.
An intersection type is not reifiable.
The decision not to make all generic types reifiable is one of the most crucial, and controversial design decisions involving the type system of the Java programming language.
Ultimately, the most important motivation for this decision is compatibility with existing code. In a naive sense, the addition of new constructs such as generics has no implications for pre-existing code. The Java programming language, per se, is compatible with earlier versions as long as every program written in the previous versions retains its meaning in the new version. However, this notion, which may be termed language compatibility, is of purely theoretical interest. Real programs (even trivial ones, such as "Hello World") are composed of several compilation units, some of which are provided by the Java SE Platform (such as elements of java.lang or java.util). In practice, then, the minimum requirement is platform compatibility - that any program written for the prior version of the Java SE Platform continues to function unchanged in the new version.
One way to provide platform compatibility is to leave existing platform functionality unchanged, only adding new functionality. For example, rather than modify the existing Collections hierarchy in java.util, one might introduce a new library utilizing generics.
The disadvantages of such a scheme is that it is extremely difficult for pre-existing clients of the Collection library to migrate to the new library. Collections are used to exchange data between independently developed modules; if a vendor decides to switch to the new, generic, library, that vendor must also distribute two versions of their code, to be compatible with their clients. Libraries that are dependent on other vendors code cannot be modified to use generics until the supplier's library is updated. If two modules are mutually dependent, the changes must be made simultaneously.
Clearly, platform compatibility, as outlined above, does not provide a realistic path for adoption of a pervasive new feature such as generics. Therefore, the design of the generic type system seeks to support migration compatibility. Migration compatibility allows the evolution of existing code to take advantage of generics without imposing dependencies between independently developed software modules.
The price of migration compatibility is that a full and sound reification of the generic type system is not possible, at least while the migration is taking place.
4.8. Raw Types
To facilitate interfacing with non-generic legacy code, it is possible to use as a type the erasure (§4.6) of a parameterized type (§4.5) or the erasure of an array type (§10.1) whose element type is a parameterized type. Such a type is called a raw type.
More precisely, a raw type is defined to be one of:
The reference type that is formed by taking the name of a generic class or interface declaration without an accompanying type argument list.
An array type whose element type is a raw type.
The name of an inner member class of a raw type R that is not inherited from a superclass or superinterface of R.
The type of a non-generic class or interface is not a raw type.
To see why the name of an inner member class of a raw type is considered raw, consider the following example:
class Outer<T>{
T t;
class Inner {
T setOuterT(T t1) { t = t1; return t; }
}
}
The type of the member(s) of Inner depends on the type parameter of Outer. If Outer is raw, Inner must be treated as raw as well, as there is no valid binding for T.
This rule applies only to inner member classes that are not inherited. Inherited inner member classes that depend on type variables will be inherited as raw types as a consequence of the rule that the supertypes of a raw type are erased, described later in this section.
Another implication of the rules above is that a generic inner class of a raw type can itself only be used as a raw type:
class Outer<T>{
class Inner<S> {
S s;
}
}
It is not possible to access Inner as a partially raw type (a "rare" type):
Outer.Inner<Double> x = null; // illegal
Double d = x.s;
because Outer itself is raw, hence so are all its inner classes including Inner, and so it is not possible to pass any type arguments to Inner.
The superclass types (respectively, superinterface types) of a raw type are the erasures of the superclass types (superinterface types) of the named class or interface.
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the generic class or interface C.
The type of an inherited instance method or non-static field of a raw type C, where the member was declared in a class or interface D, is the type of the member in the supertype of C that names D.
The type of a static method or static field of a raw type C is the same as its type in the generic class or interface C.
It is a compile-time error to pass type arguments to a non-static member class or interface of a raw type that is not inherited from its superclasses or superinterfaces.
It is a compile-time error to attempt to use a member class or interface of a parameterized type as a raw type.
This means that the ban on "rare" types extends to the case where the qualifying type is parameterized, but we attempt to use the inner class as a raw type:
Outer<Integer>.Inner x = null; // illegal
This is the opposite of the case discussed above. There is no practical justification for this half-baked type. In legacy code, no type arguments are used. In non-legacy code, we should use the generic types correctly and pass all the required type arguments.
The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of generics into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.
To make sure that potential violations of the typing rules are always flagged, some accesses to members of a raw type will result in compile-time unchecked warnings. The rules for compile-time unchecked warnings when accessing members or constructors of raw types are as follows:
At an assignment to a field: if the type of the Primary in the field access expression (§15.11) is a raw type, then a compile-time unchecked warning occurs if erasure changes the field's type.
At an invocation of a method or constructor: if the type of the class or interface to search (§15.12.1) is a raw type, then a compile-time unchecked warning occurs if erasure changes any of the formal parameter types of the method or constructor.
No compile-time unchecked warning occurs for a method call when the formal parameter types do not change under erasure (even if the return type and/or throws clause changes), for reading from a field, or for a class instance creation of a raw type.
Note that the unchecked warnings above are distinct from the unchecked warnings possible from narrowing reference conversion (§5.1.6), unchecked conversion (§5.1.9), method declarations (§8.4.1, §8.4.8.3), and certain expressions (§15.12.4.2, §15.13.2, §15.27.3).
The warnings here cover the case where a legacy consumer uses a generified library. For example, the library declares a generic class Foo<T extends String> that has a field f of type Vector<T>, but the consumer assigns a vector of integers to e.f where e has the raw type Foo. The legacy consumer receives a warning because it may have caused heap pollution (§4.12.2) for generified consumers of the generified library.
(Note that the legacy consumer can assign a Vector<String> from the library to its own Vector variable without receiving a warning. That is, the subtyping rules (§4.10.2) of the Java programming language make it possible for a variable of a raw type to be assigned a value of any of the type's parameterized instances.)
The warnings from unchecked conversion cover the dual case, where a generified consumer uses a legacy library. For example, a method of the library has the raw return type Vector, but the consumer assigns the result of the method invocation to a variable of type Vector<String>. This is unsafe, since the raw vector might have had a different element type than String, but is still permitted using unchecked conversion in order to enable interfacing with legacy code. The warning from unchecked conversion indicates that the generified consumer may experience problems from heap pollution at other points in the program.
Example 4.8-1. Raw Types
class Cell<E> {
E value;
Cell(E v) { value = v; }
E get() { return value; }
void set(E v) { value = v; }
public static void main(String[] args) {
Cell x = new Cell<String>("abc");
System.out.println(x.value); // OK, has type Object
System.out.println(x.get()); // OK, has type Object
x.set("def"); // unchecked warning
}
}
Example 4.8-2. Raw Types and Inheritance
import java.util.ArrayList;