File: nullness-checker.tex

package info (click to toggle)
checker-framework-java 3.2.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,104 kB
  • sloc: java: 145,916; xml: 839; sh: 518; makefile: 404; perl: 26
file content (1961 lines) | stat: -rw-r--r-- 79,777 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
\htmlhr
\chapterAndLabel{Nullness Checker}{nullness-checker}

If the Nullness Checker issues no warnings for a given program, then
running that program will never throw a null pointer exception.  This
guarantee enables a programmer to prevent errors from occurring when a
program is run.  See Section~\ref{nullness-checks} for more details about
the guarantee and what is checked.

The most important annotations supported by the Nullness Checker are
\refqualclass{checker/nullness/qual}{NonNull} and
\refqualclass{checker/nullness/qual}{Nullable}.
\refqualclass{checker/nullness/qual}{NonNull} is rarely written, because it is
the default.  All of the annotations are explained in
Section~\ref{nullness-annotations}.

To run the Nullness Checker, supply the
\code{-processor org.checkerframework.checker.nullness.NullnessChecker}
command-line option to javac.  For
examples, see Section~\ref{nullness-example}.

The NullnessChecker is actually an ensemble of three pluggable
type-checkers that work together: the Nullness Checker proper (which is the
main focus of this chapter), the Initialization Checker
(Section~\ref{initialization-checker}), and the Map Key Checker
(\chapterpageref{map-key-checker}).
Their type hierarchies are completely independent, but they work together
to provide precise nullness checking.


\sectionAndLabel{What the Nullness Checker checks}{nullness-checks}

The checker issues a warning in these cases:

\begin{enumerate}

\item
  When an expression of non-\refqualclass{checker/nullness/qual}{NonNull} type
  is dereferenced, because it might cause a null pointer exception.
  Dereferences occur not only when a field is accessed, but when an array
  is indexed, an exception is thrown, a lock is taken in a synchronized
  block, and more.  For a complete description of all checks performed by
  the Nullness Checker, see the Javadoc for
  \refclass{checker/nullness}{NullnessVisitor}.

\item
  When an expression of \refqualclass{checker/nullness/qual}{NonNull} type
  might become null, because it
  is a misuse of the type:  the null value could flow to a dereference that
  the checker does not warn about.

  As a special case of an of \refqualclass{checker/nullness/qual}{NonNull}
  type becoming null, the checker also warns whenever a field of
  \refqualclass{checker/nullness/qual}{NonNull} type is not initialized in a
  constructor.

\end{enumerate}

This example illustrates the programming errors that the checker detects:

\begin{Verbatim}
  @Nullable Object   obj;  // might be null
  @NonNull  Object nnobj;  // never null
  ...
  obj.toString()         // checker warning:  dereference might cause null pointer exception
  nnobj = obj;           // checker warning:  nnobj may become null
  if (nnobj == null)     // checker warning:  redundant test
\end{Verbatim}

Parameter passing and return values are checked analogously to assignments.

The Nullness Checker also checks the correctness, and correct use, of
initialization (see
Section~\ref{initialization-checker}) and of map key annotations (see
\chapterpageref{map-key-checker}).


The checker performs additional checks if certain \code{-Alint}
command-line options are provided.  (See
Section~\ref{alint} for more details about the \code{-Alint}
command-line option.)


\subsectionAndLabel{Nullness Checker optional warnings}{nullness-lint}

\begin{enumerate}
\item
  Options that control soundness:

\begin{itemize}
\item
  \label{nullness-lint-soundArrayCreationNullness}%
  \label{nullness-lint-nonnullarraycomponents}% temporary, for backward compatibility
  If you supply the \code{-Alint=soundArrayCreationNullness} command-line
  option, then the checker warns if it encounters an array creation
  with a non-null component type.
  See Section~\ref{nullness-arrays} for a discussion.
  % TODO: this option is temporary and the sound option
  % should become the default.
\end{itemize}

\item
  Options that warn about poor code style:

\begin{itemize}
\item
  \label{nullness-lint-nulltest}%
  If you supply the \code{-Alint=redundantNullComparison} command-line option, then the
  checker warns when a null check is performed against a value that is
  guaranteed to be non-null, as in \code{("m" == null)}.  Such a check is
  unnecessary and might indicate a programmer error or misunderstanding.
  The lint option is disabled by default because sometimes such checks are
  part of ordinary defensive programming.
\end{itemize}

\end{enumerate}


\sectionAndLabel{Nullness annotations}{nullness-annotations}

The Nullness Checker uses three separate type hierarchies:  one for nullness,
one for initialization (Section~\ref{initialization-checker}),
and one for map keys (\chapterpageref{map-key-checker})
The Nullness Checker has four varieties of annotations:  nullness
type qualifiers, nullness method annotations, initialization type qualifiers, and
map key type
qualifiers.

\subsectionAndLabel{Nullness qualifiers}{nullness-qualifiers}

The nullness hierarchy contains these qualifiers:

\begin{description}

\item[\refqualclass{checker/nullness/qual}{Nullable}]
  indicates a type that includes the null value.  For example, the type \code{Boolean}
  is nullable:  a variable of type \code{Boolean} always has one of the
  values \code{TRUE}, \code{FALSE}, or \code{null}.

\item[\refqualclass{checker/nullness/qual}{NonNull}]
  indicates a type that does not include the null value.  The type
  \code{boolean} is non-null; a variable of type \code{boolean} always has
  one of the values \code{true} or \code{false}.  The type \code{@NonNull
    Boolean} is also non-null:  a variable of type \code{@NonNull Boolean}
  always has one of the values \code{TRUE} or \code{FALSE} --- never
  \code{null}.  Dereferencing an expression of non-null type can never cause
  a null pointer exception.

  The \<@NonNull> annotation is rarely written in a program, because it is
  the default (see Section~\ref{null-defaults}).

\item[\refqualclass{checker/nullness/qual}{PolyNull}]
  indicates qualifier polymorphism.  For a description of
  \refqualclass{checker/nullness/qual}{PolyNull}, see
  Section~\ref{qualifier-polymorphism}.

\item[\refqualclass{checker/nullness/qual}{MonotonicNonNull}]
  indicates a reference that may be \code{null}, but if it ever becomes
  non-\code{null}, then it never becomes \code{null} again.  This is
  appropriate for lazily-initialized fields, for field initialization that
  occurs in a lifecycle method other than the constructor (e.g., an
  override of \<android.app.Activity.onCreate>), and other uses.  When the
  variable is read, its type is treated as
  \refqualclass{checker/nullness/qual}{Nullable}, but when the variable is
  assigned, its type is treated as
  \refqualclass{checker/nullness/qual}{NonNull}.

  \begin{sloppypar}
  Because the Nullness Checker works intraprocedurally (it analyzes one
  method at a time), when a \code{MonotonicNonNull} field is first read within a
  method, the field cannot be assumed to be non-null.  The benefit of
  MonotonicNonNull over Nullable is its different interaction with
  type refinement (Section~\ref{type-refinement}).
  After a check of a MonotonicNonNull
  field, all subsequent accesses \emph{within that method} can be assumed
  to be NonNull, even after arbitrary external method calls that have
  access to the given field.
  \end{sloppypar}

  It is permitted to initialize a MonotonicNonNull field to null, but the
  field may not be assigned to null anywhere else in the program.  If you
  supply the \<noInitForMonotonicNonNull> lint flag (for example, supply
  \<-Alint=noInitForMonotonicNonNull> on the command line), then
  \<@MonotonicNonNull> fields are not allowed to have initializers at their
  declarations.

  Use of \<@MonotonicNonNull> on a static field is a code smell:  it may
  indicate poor design.  You should consider whether it is possible to make
  the field a member field that is set in the constructor.

\end{description}

Figure~\ref{fig-nullness-hierarchy} shows part of the type hierarchy for the
Nullness type system.
(The annotations exist only at compile time; at run time, Java has no
multiple inheritance.)

\begin{figure}
\includeimage{nullness}{3.5cm}
\caption{Partial type hierarchy for the Nullness type system.
Java's \<Object> is expressed as \<@Nullable Object>.  Programmers can omit
most type qualifiers, because the default annotation
(Section~\ref{null-defaults}) is usually correct.
The Nullness Checker verifies three type hierarchies:  this one for
nullness, one for initialization (Section~\ref{initialization-checker}),
and one for map keys (\chapterpageref{map-key-checker}).}
\label{fig-nullness-hierarchy}
\end{figure}


\subsectionAndLabel{Nullness method annotations}{nullness-method-annotations}

The Nullness Checker supports several annotations that specify method
behavior.  These are declaration annotations, not type annotations:  they
apply to the method itself rather than to some particular type.

\begin{description}

\item[\refqualclass{checker/nullness/qual}{RequiresNonNull}]
  indicates a method precondition:  The annotated method expects the
  specified variables to be non-null when the
  method is invoked.  Don't use this for formal parameters (just annotate
  their type as \<@NonNull>).  \<@RequiresNonNull> is appropriate for
  a field that is \<@Nullable> in general, but some method requires the
  field to be non-null.

\item[\refqualclass{checker/nullness/qual}{EnsuresNonNull}]
\item[\refqualclass{checker/nullness/qual}{EnsuresNonNullIf}]
  indicates a method postcondition.  With \<@EnsuresNonNull>, the given
  expressions are non-null after the method returns; this is useful for a
  method that initializes a field, for example.  With
  \<@EnsuresNonNullIf>, if the annotated
  method returns the given boolean value (true or false), then the given
  expressions are non-null.  See Section~\ref{conditional-nullness} and the
  Javadoc for examples of their use.

\end{description}


\subsectionAndLabel{Initialization qualifiers}{initialization-qualifiers-overview}

The Nullness Checker invokes an Initialization Checker, whose annotations indicate whether
an object is fully initialized --- that is, whether all of its fields have
been assigned.

\begin{description}
\item[\refqualclass{checker/initialization/qual}{Initialized}]
\item[\refqualclass{checker/initialization/qual}{UnknownInitialization}]
\item[\refqualclass{checker/initialization/qual}{UnderInitialization}]
\end{description}

\noindent
Use of these annotations can help you to type-check more
code.  Figure~\ref{fig-initialization-hierarchy} shows its type hierarchy.  For
details, see Section~\ref{initialization-checker}.


\subsectionAndLabel{Map key qualifiers}{map-key-qualifiers}

\begin{description}
\item[\refqualclass{checker/nullness/qual}{KeyFor}]
\end{description}
    indicates that a value is a key for a given map --- that is, indicates
    whether \code{map.containsKey(value)} would evaluate to \code{true}.

This annotation is checked by a Map Key Checker
(\chapterpageref{map-key-checker}) that the Nullness Checker
invokes.  The \refqualclass{checker/nullness/qual}{KeyFor} annotation enables
the Nullness Checker to treat calls to
\sunjavadoc{java.base/java/util/Map.html\#get(java.lang.Object)}{\code{Map.get}}
precisely rather than assuming it may always return null.  In particular,
a call \<mymap.get(mykey)> returns a non-\<null> value if two conditions
are satisfied:
\begin{enumerate}
\item \<mymap>'s values are all non-\<null>; that is, \<mymap> was
  declared as \code{Map<\emph{KeyType}, @NonNull \emph{ValueType}>}.  Note
  that \<@NonNull> is the default type, so it need not be written explicitly.
\item \<mykey> is a key in \<mymap>; that is, \<mymap.containsKey(mykey)>
  returns \<true>.  You express this fact to the Nullness Checker by
  declaring \<mykey> as \<@KeyFor("mymap") \emph{KeyType} mykey>.  For a
  local variable, you generally do not need to write the
  \<@KeyFor("mymap")> type qualifier, because it can be inferred.
\end{enumerate}
\noindent
If either of these two conditions is violated, then \<mymap.get(mykey)> has
the possibility of returning \<null>.

\sectionAndLabel{Writing nullness annotations}{writing-nullness-annotations}

\subsectionAndLabel{Implicit qualifiers}{nullness-implicit-qualifiers}

The Nullness Checker
adds implicit qualifiers, reducing the number of annotations that must
appear in your code (see Section~\ref{effective-qualifier}).
For example, enum types are implicitly non-null, so you never need to write
\<@NonNull MyEnumType>.

If you want details about implicitly-added nullness qualifiers, see the
implementation of \refclass{checker/nullness}{NullnessAnnotatedTypeFactory}.



\subsectionAndLabel{Default annotation}{null-defaults}

Unannotated references are treated as if they had a default annotation.
The standard defaulting rule is CLIMB-to-top,  described in
Section~\ref{climb-to-top}.  Its effect is to default all types to
\<@NonNull>, except that \<@Nullable> is used for casts, locals,
instanceof, and implicit bounds.  A user can choose a different defaulting
rule by writing a \refqualclass{framework/qual}{DefaultQualifier} annotation on a
 package, class, or method.  In the example below, fields are defaulted to
\<@Nullable> instead of \<@NonNull>.

\begin{Verbatim}
@DefaultQualifier(value = Nullable.class, locations = TypeUseLocation.FIELD)
class MyClass {
    Object nullableField = null;
    @NonNull Object nonNullField = new Object();
}
\end{Verbatim}


%% Cut this to shorten the section.  Most users won't care about it.
% %BEGIN LATEX
% \begin{sloppy}
% %END LATEX
% Here are three possible default rules you may wish to use.  Other rules are
% possible but are not as useful.
% \begin{itemize}
% \item
%   \refqualclass{checker/nullness/qual}{Nullable}:  Unannotated types are regarded as possibly-null, or
%   nullable.  This default is backward-compatible with Java, which permits
%   any reference to be null.  You can activate this default by writing
%   a \code{@DefaultQualifier(Nullable.class)} annotation on a
%   % package/
%   class or method
%   % /variable
%   declaration.
% \item
%   \refqualclass{checker/nullness/qual}{NonNull}:  Unannotated types are treated as non-null.
%   % This may leads to fewer annotations written in your code.
%   You can activate this
%   default via the
%   \code{@DefaultQualifier(NonNull.class)} annotation.
% \item
%   Non-null except locals (NNEL):  Unannotated types are treated as
%   \refqualclass{checker/nullness/qual}{NonNull}, \emph{except} that the
%   unannotated raw type of a local variable is treated as
%   \refqualclass{checker/nullness/qual}{Nullable}.  (Any generic arguments to a
%   local variable still default to
%   \refqualclass{checker/nullness/qual}{NonNull}.)  This is the standard
%   behavior.  You can explicitly activate this default via the
%   \code{@DefaultQualifier(value=NonNull.class,
%     locations=\discretionary{}{}{}\{DefaultLocation\discretionary{}{}{}.ALL\_EXCEPT\_LOCALS\})}
%   annotation.
%
%   The NNEL default leads to the smallest number of explicit annotations in
%   your code~\cite{PapiACPE2008}.  It is what we recommend.  If you do not
%   explicitly specify a different default, then NNEL is the default.
% \end{itemize}
% %BEGIN LATEX
% \end{sloppy}
% %END LATEX


\subsectionAndLabel{Conditional nullness}{conditional-nullness}

The Nullness Checker supports a form of conditional nullness types, via the
\refqualclass{checker/nullness/qual}{EnsuresNonNullIf} method annotations.
The annotation on a method declares that some expressions are non-null, if
the method returns true (false, respectively).

Consider \sunjavadoc{java.base/java/lang/Class.html}{java.lang.Class}.
Method
\sunjavadoc{java.base/java/lang/Class.html\#getComponentType()}{Class.getComponentType()}
may return null, but it is specified to return a non-null value if
\sunjavadoc{java.base/java/lang/Class.html\#isArray()}{Class.isArray()} is
true.
You could declare this relationship in the following way (this particular
example is already
done for you in the annotated JDK that comes with the Checker Framework):

\begin{Verbatim}
  class Class<T> {
    @EnsuresNonNullIf(expression="getComponentType()", result=true)
    public native boolean isArray();

    public native @Nullable Class<?> getComponentType();
  }
\end{Verbatim}

A client that checks that a \code{Class} reference is indeed that of an array,
can then de-reference the result of \code{Class.getComponentType} safely
without any nullness check.  The Checker Framework source code itself
uses such a pattern:

\begin{Verbatim}
    if (clazz.isArray()) {
      // no possible null dereference on the following line
      TypeMirror componentType = typeFromClass(clazz.getComponentType());
      ...
    }
\end{Verbatim}

Another example is \sunjavadoc{java.base/java/util/Queue.html\#peek()}{Queue.peek}
and \sunjavadoc{java.base/java/util/Queue.html\#poll()}{Queue.poll}, which return
non-null if \sunjavadoc{java.base/java/util/Collection.html\#isEmpty()}{isEmpty}
returns false.

The argument to \code{@EnsuresNonNullIf} is a Java expression, including method calls
(as shown above), method formal parameters, fields, etc.; for details, see
Section~\ref{java-expressions-as-arguments}.
More examples of the use of these annotations appear in the Javadoc for
\refqualclass{checker/nullness/qual}{EnsuresNonNullIf}.


\subsectionAndLabel{Nullness and arrays}{nullness-arrays}

Suppose that you declare an array to contain non-null elements.
Currently, the Nullness Checker does not verify that all the elements of the
array are initialized to a non-null value.  This is an unsoundness in the
checker.

To make the Nullness Checker conservatively reject code that may leave a
non-null value in an array, use the command-line option
\code{-Alint=soundArrayCreationNullness}.  The option is currently disabled
because it makes the checker issue many false positive errors.
% TODO: flip the default after collecting more data.

When the \code{-Alint=soundArrayCreationNullness} option is supplied,
the following is not allowed:

\begin{Verbatim}
  Object [] oa = new Object[10]; // error
\end{Verbatim}

\noindent
(recall that \<Object> means the same thing as \<@NonNull Object>).

Instead, your code needs to create a nullable or lazy-nonnull array, initialize
each component, and then assign the result to a non-null array:

\begin{Verbatim}
  @MonotonicNonNull Object [] temp = new @MonotonicNonNull Object[10];
  for (int i = 0; i < temp.length; ++i) {
    temp[i] = new Object();
  }
  @SuppressWarnings("nullness") // temp array is now fully initialized
  @NonNull Object [] oa = temp;
\end{Verbatim}

Note that the checker is currently not powerful enough to ensure that
each array component was initialized. Therefore, the last assignment
needs to be trusted:  that is, a programmer must verify that it is safe,
then write a \<@SuppressWarnings> annotation.

% TODO: explain more aspects, give more examples.



\subsectionAndLabel{Run-time checks for nullness}{nullness-runtime-checks}

When you perform a run-time check for nullness, such as \<if (x != null)
...>, then the Nullness Checker refines the type of \<x> to
\<@NonNull>.  The refinement lasts until the end of the scope of the test
or until \<x> may be side-effected.  For more details, see
Section~\ref{type-refinement}.


\subsectionAndLabel{Additional details}{nullness-additional-details}

The Nullness Checker does some special checks in certain circumstances, in
order to soundly reduce the number of warnings that it produces.

For example, a call to
\sunjavadoc{java.base/java/lang/System.html\#getProperty(java.lang.String)}{System.getProperty(String)}
can return null in general, but it will not return null if the argument is
one of the built-in-keys listed in the documentation of
\sunjavadoc{java.base/java/lang/System.html\#getProperties()}{System.getProperties()}.
The Nullness Checker is aware of this fact, so you do not have to suppress
a warning for a call like \<System.getProperty("line.separator")>.  The
warning is still issued for code like this:

\begin{Verbatim}
  final String s = "line.separator";
  nonNullvar = System.getProperty(s);
\end{Verbatim}

\noindent
though that case could be handled as well, if desired.
(Suppression of the warning is, strictly speaking, not sound, because a
library that your code calls, or your code itself, could perversely change
the system properties; the Nullness Checker assumes this bizarre coding
pattern does not happen.)
(It is better style to use \<System.lineSeparator()> than the call to
\<System.getProperty("line.separator")> anyway.)


\subsectionAndLabel{Inference of \code{@NonNull} and \code{@Nullable} annotations}{nullness-inference}

It can be tedious to write annotations in your code.  Tools exist that
can automatically infer annotations and insert them in your source code.
(This is different than type qualifier refinement for local variables
(Section~\ref{type-refinement}), which infers a more specific type for
local variables and uses them during type-checking but does not insert them
in your source code.  Type qualifier refinement is always enabled, no
matter how annotations on signatures got inserted in your source code.)

Your choice of tool depends on what default annotation (see
Section~\ref{null-defaults}) your code uses.  You only need one of these tools.

\begin{itemize}

\item
  Inference of \refqualclass{checker/nullness/qual}{Nullable}:
  %
  If your code uses the standard CLIMB-to-top default (Section~\ref{climb-to-top}) or
  the NonNull default, then use the
  \href{http://plse.cs.washington.edu/daikon/download/doc/daikon.html#AnnotateNullable}{AnnotateNullable}
  tool of the \href{http://plse.cs.washington.edu/daikon/}{Daikon invariant
    detector}.

\item
  Inference of \refqualclass{checker/nullness/qual}{NonNull}:
  %
  If your code uses the Nullable default, use one of these tools:
\begin{itemize}
\item
  \href{https://juliasoft.com/solutions/}{Julia analyzer},
\item
  \href{http://nit.gforge.inria.fr}{Nit: Nullability Inference Tool},
\item
  \href{http://jastadd.org/jastadd-tutorial-examples/non-null-types-for-java/}{Non-null
    checker and inferencer} of the \href{http://jastadd.org/}{JastAdd
    Extensible Compiler}.
\end{itemize}

\end{itemize}



\sectionAndLabel{Suppressing nullness warnings}{suppressing-warnings-nullness}

When the Nullness Checker reports a warning, it's best to change the code
or its annotations, to eliminate the warning.  Alternately, you can
suppress the warning, which does not change the code but prevents the
Nullness Checker from reporting this particular warning to you.

\begin{sloppypar}
The Checker Framework supplies several ways to suppress warnings, most
notably the \<@SuppressWarnings("nullness")> annotation (see
Chapter~\ref{suppressing-warnings}).  An example use is
\end{sloppypar}

%BEGIN LATEX
\begin{smaller}
%END LATEX
\begin{Verbatim}
    // might return null
    @Nullable Object getObject(...) { ... }

    void myMethod() {
      @SuppressWarnings("nullness") // with argument x, getObject always returns a non-null value
      @NonNull Object o2 = getObject(x);
\end{Verbatim}
%BEGIN LATEX
\end{smaller}
%END LATEX


The Nullness Checker supports an additional warning suppression key,
\<nullness:generic.argument>.
Use of \<@SuppressWarnings("nullness:generic.argument")> causes the Nullness
Checker to suppress warnings related to misuse of generic type
arguments.  One use for this key is when a class is declared to take only
\<@NonNull> type arguments, but you want to instantiate the class with a
\<@Nullable> type argument, as in \code{List<@Nullable Object>}.

The Nullness Checker also permits you to use assertions or method calls to
suppress warnings; see below.

% TODO: check whether the SuppressWarnings keys are correct.


\subsectionAndLabel{Suppressing warnings with assertions and method calls}{suppressing-warnings-with-assertions}

Occasionally, it is inconvenient or
verbose to use the \<@SuppressWarnings> annotation.  For example, Java does
not permit annotations such as \<@SuppressWarnings> to appear on statements.
In such cases, you can use the \<@AssumeAssertion> string in
an \<assert> message (see Section~\ref{assumeassertion}).

If you need to suppress a warning within an expression, then
sometimes writing an assertion is not convenient.  In such a case,
you can suppress warnings by writing a call to the
\refmethod{checker/nullness}{NullnessUtil}{castNonNull}{-T-} method.
The rest of this section discusses the \<castNonNull> method.

The Nullness Checker considers both the return value, and also the
argument, to be non-null after the \<castNonNull> method call.
The Nullness Checker issues no warnings in any of the following
code:

\begin{Verbatim}
  // One way to use castNonNull as a cast:
  @NonNull String s = castNonNull(possiblyNull1);

  // Another way to use castNonNull as a cast:
  castNonNull(possiblyNull2).toString();

  // It is possible, but not recommmended, to use castNonNull as a statement:
  // (It would be better to write an assert statement with @AssumeAssertion
  // in its message, instead.)
  castNonNull(possiblyNull3);
  possiblyNull3.toString();
\end{Verbatim}

  The \<castNonNull> method throws \<AssertionError> if Java assertions are enabled and
  the argument is \<null>.  However, it is not intended for general defensive
  programming; see Section~\ref{defensive-programming}.

  To use the \<castNonNull> method, the \<checker-qual.jar> file
  must be on the classpath at run time.

\begin{sloppypar}
The Nullness Checker introduces a new method, rather than re-using an
existing method such as \<org.junit.Assert.assertNotNull(Object)> or
\<com.google.common.base.Preconditions.checkNotNull(Object)>.  Those
methods are commonly used for defensive programming, so it is impossible to
know the programmer's intent when writing them.  Therefore, it is important to
have a method call that is used only for warning suppression.  See
Section~\ref{defensive-programming} for a discussion of
the distinction between warning suppression and defensive programming.
% Also, different checking tools issue different false warnings that
% need to be suppressed, so warning suppression needs to be customized for
% each tool.
\end{sloppypar}


\sectionAndLabel{Examples}{nullness-example}

\subsectionAndLabel{Tiny examples}{nullness-tiny-examples}

To try the Nullness Checker on a source file that uses the \refqualclass{checker/nullness/qual}{NonNull} qualifier,
use the following command (where \code{javac} is the Checker Framework compiler that
is distributed with the Checker Framework):

%BEGIN LATEX
\begin{smaller}
%END LATEX
\begin{Verbatim}
  javac -processor org.checkerframework.checker.nullness.NullnessChecker docs/examples/NullnessExample.java
\end{Verbatim}
%BEGIN LATEX
\end{smaller}
%END LATEX

\noindent
Compilation will complete without warnings.

To see the checker warn about incorrect usage of annotations (and therefore the
possibility of a null pointer exception at run time), use the following command:

\begin{mysmall}
\begin{Verbatim}
  javac -processor org.checkerframework.checker.nullness.NullnessChecker docs/examples/NullnessExampleWithWarnings.java
\end{Verbatim}
\end{mysmall}


\noindent
The compiler will issue two warnings regarding violation of the semantics of
\refqualclass{checker/nullness/qual}{NonNull}.
% in the \code{NonNullExampleWithWarnings.java} file.


\subsectionAndLabel{Example annotated source code}{nullness-annotated-library}

Some libraries that are annotated with nullness qualifiers are:

\begin{itemize}
\item
The Nullness Checker itself.

\item
The Java projects in the \href{https://github.com/plume-lib/}
{plume-lib GitHub organization}.
Type-checking occurs on each build.

\item
The
\href{http://plse.cs.washington.edu/daikon/}{Daikon invariant detector}.
Run the command \code{make check-nullness}.

\end{itemize}


\sectionAndLabel{Tips for getting started}{nullness-getting-started}

Here are some tips about getting started using the Nullness Checker on a
legacy codebase.  For more generic advice (not specific to the Nullness
Checker), see Section~\ref{get-started-with-legacy-code}.

Your goal is to add \refqualclass{checker/nullness/qual}{Nullable} annotations
to the types of any variables that can be null.  (The default is to assume
that a variable is non-null unless it has a \code{@Nullable} annotation.)
Then, you will run the Nullness Checker.  Each of its errors indicates
either a possible null pointer exception, or a wrong/missing annotation.
When there are no more warnings from the checker, you are done!

We recommend that you start by searching the code for occurrences of
\code{null} in the following locations; when you find one, write the
corresponding annotation:

\begin{itemize}
\item
  in Javadoc:  add \code{@Nullable} annotations to method signatures (parameters and return types).
% Search for "\*.*\bnull\b"
\item
  \code{return null}:  add a \code{@Nullable} annotation to the return type
  of the given method.
% Search for "return null" and "return.*? null" and "return.*: null"
\item
  \code{\emph{param} == null}:  when a formal parameter is compared to
  \code{null}, then in most cases you can add a \code{@Nullable} annotation
  to the formal parameter's type
\item
  \code{\emph{TypeName} \emph{field} = null;}:  when a field is initialized to
  \code{null} in its declaration, then it needs either a
  \refqualclass{checker/nullness/qual}{Nullable} or a
  \refqualclass{checker/nullness/qual}{MonotonicNonNull} annotation.  If the field
  is always set to a non-null value in the constructor, then you can just
  change the declaration to \code{\emph{Type} \emph{field};}, without an
  initializer, and write no type annotation (because the default is
  \<@NonNull>).
\item
  declarations of \<contains>, \<containsKey>, \<containsValue>, \<equals>,
  \<get>, \<indexOf>, \<lastIndexOf>, and \<remove> (with \<Object> as the
  argument type):
  change the argument type to \<@Nullable Object>; for \<remove>, also change
  the return type to \<@Nullable Object>.
% Emacs code that adds annotations to the argument types:
% ;;NOT: (tags-query-replace " apply(Object " " apply(@Nullable Object ")
% (tags-query-replace " \\(get\\|equals\\|remove\\|contains\\|containsValue\\|containsKey\\|indexOf\\|lastIndexOf\\)(Object " " \\1(@Nullable Object ")

\end{itemize}

\noindent
You should ignore all other occurrences of \code{null} within a method
body.  In particular, you rarely need to annotate local variables
(except their type arguments or array element types).

Only after this step should you run
the Nullness Checker.  The reason is that it is quicker to search for
places to change than to repeatedly run the checker and fix the errors it
tells you about, one at a time.

Here are some other tips:
\begin{itemize}
\item
    \begin{sloppypar}
    In any file where you write an annotation such as \code{@Nullable},
    don't forget to add \code{import org.checkerframework.checker.nullness.qual.*;}.
    \end{sloppypar}
\item
    To indicate an array that can be null, write, for example: \code{int
      @Nullable []}. \\
    By contrast, \code{@Nullable Object []} means a non-null array that
    contains possibly-null objects.
\item
    If you know that a particular variable is definitely not null, but the
    Nullness Checker estimates that the variable might be null, then you can
    make the Nullness Checker trust your judgment by writing
    an assertion (see Section~\ref{assumeassertion}):
\begin{Verbatim}
assert var != null : "@AssumeAssertion(nullness)";
\end{Verbatim}
\item
    To indicate that a routine returns the same value every time it is
    called, use \refqualclass{dataflow/qual}{Pure} (see Section~\ref{type-refinement-purity}).
\item
    To indicate a method precondition (a contract stating the conditions
    under which a client is allowed to call it), you can use annotations
    such as \refqualclass{checker/nullness/qual}{RequiresNonNull} (see Section~\ref{nullness-method-annotations}).
\end{itemize}



\sectionAndLabel{Other tools for nullness checking}{nullness-related-work}

\newcommand{\linktoNonNull}{\refclass{checker/nullness/qual}{NonNull}}
\newcommand{\linktoNullable}{\refclass{checker/nullness/qual}{Nullable}}

The Checker Framework's nullness annotations are similar to annotations used
in other
tools.
You might prefer to use the Checker Framework because it has a more
powerful analysis that can warn you about more null pointer errors in your
code.
Most of the other tools are bug-finding tools rather than verification tools, since they
give up precision, soundness, or both in favor of being fast and
easy to use.  Also
see Section~\ref{faq-type-checking-vs-bug-detectors} for a comparison to other tools.

If your code is already annotated with a different nullness
annotation, the Checker Framework can type-check your code.
It treats annotations from other tools
as if you had written the corresponding annotation from the
Nullness Checker, as described in Figure~\ref{fig-nullness-refactoring}.
If the other annotation is a declaration annotation, it may be moved; see
Section~\ref{declaration-annotations-moved}.


% These lists should be kept in sync with
% ../../checker/src/main/java/org/checkerframework/checker/nullness/NullnessAnnotatedTypeFactory.java
\begin{figure}
\begin{center}
% The ~ around the text makes things look better in Hevea (and not terrible
% in LaTeX).
\begin{tabular}{ll}
\begin{tabular}{|l|}
\hline
 ~android.annotation.NonNull~ \\ \hline
 ~android.support.annotation.NonNull~ \\ \hline
 ~androidx.annotation.NonNull~ \\ \hline
 ~androidx.annotation.RecentlyNonNull~ \\ \hline
 ~com.sun.istack.internal.NotNull~ \\ \hline
 ~edu.umd.cs.findbugs.annotations.NonNull~ \\ \hline
 ~io.reactivex.annotations.NonNull~ \\ \hline
 ~javax.annotation.Nonnull~ \\ \hline
 ~javax.validation.constraints.NotNull~ \\ \hline
 ~lombok.NonNull~ \\ \hline
 ~org.checkerframework.checker.nullness.compatqual.NonNullDecl~ \\ \hline
 ~org.checkerframework.checker.nullness.compatqual.NonNullType~ \\ \hline
 ~org.eclipse.jdt.annotation.NonNull~ \\ \hline
 ~org.eclipse.jgit.annotations.NonNull~ \\ \hline
 ~org.jetbrains.annotations.NotNull~ \\ \hline
 ~org.jmlspecs.annotation.NonNull~ \\ \hline
 ~org.netbeans.api.annotations.common.NonNull~ \\ \hline
 ~org.springframework.lang.NonNull~ \\ \hline
\end{tabular}
&
$\Rightarrow$
~org.checkerframework.checker.nullness.qual.NonNull~
\\
\
\\
\begin{tabular}{|l|l|}
\hline
 ~android.annotation.Nullable~ \\ \hline
 ~android.support.annotation.Nullable~ \\ \hline
 ~androidx.annotation.Nullable~ \\ \hline
 ~androidx.annotation.RecentlyNullable~ \\ \hline
 ~com.sun.istack.internal.Nullable~ \\ \hline
 ~edu.umd.cs.findbugs.annotations.Nullable~ \\ \hline
 ~edu.umd.cs.findbugs.annotations.CheckForNull~ \\ \hline
 ~edu.umd.cs.findbugs.annotations.PossiblyNull~ \\ \hline
 ~edu.umd.cs.findbugs.annotations.UnknownNullness~ \\ \hline
 ~io.reactivex.annotations.Nullable~ \\ \hline
 ~javax.annotation.Nullable~ \\ \hline
 ~javax.annotation.CheckForNull~ \\ \hline
 ~org.checkerframework.checker.nullness.compatqual.NullableDecl~ \\ \hline
 ~org.checkerframework.checker.nullness.compatqual.NullableType~ \\ \hline
 ~org.eclipse.jdt.annotation.Nullable~ \\ \hline
 ~org.eclipse.jgit.annotations.Nullable~ \\ \hline
 ~org.jetbrains.annotations.Nullable~ \\ \hline
 ~org.jmlspecs.annotation.Nullable~ \\ \hline
 ~org.netbeans.api.annotations.common.NullAllowed~ \\ \hline
 ~org.netbeans.api.annotations.common.CheckForNull~ \\ \hline
 ~org.netbeans.api.annotations.common.NullUnknown~ \\ \hline
 ~org.springframework.lang.Nullable~ \\ \hline
\end{tabular}
&
$\Rightarrow$
~org.checkerframework.checker.nullness.qual.Nullable~
\end{tabular}
\end{center}
%BEGIN LATEX
\vspace{-1.5\baselineskip}
%END LATEX
\caption{Correspondence between other nullness annotations and the
  Checker Framework's annotations.}
\label{fig-nullness-refactoring}
\end{figure}

%% Removed, because it's tedious and should be obvious to a decent programmer.
% Your IDE may be able to do that for you.  Alternately, do the following:
% \begin{enumerate}
% \item
%   replace \<@Nonnull> by \<@NonNull> (note capitalization difference)
% \item
%   replace \<@CheckForNull> by \<@Nullable>
% \item
%   replace \<@UnknownNullness> by \<@Nullable>
% \item
%   convert each single-type import statement (without a ``\<*>'' character)
%    according to the table above.
% \item
%   convert each on-demand import statements, such as ``\<import
%    edu.umd.cs.findbugs.annotations.*;>''.
% \begin{itemize}
%    \item
%   One approach is to change it into a set of single-type imports,
%       then convert the relevant ones.
%    \item
%   Another approach is to change it according to the table above, then
%       try to compile and re-introduce the single-type imports as necessary.
% \end{itemize}
%    These approaches let you continue to use other annotations in the
%    \<edu.umd.cs.findbugs.annotations> package, even though you are not using
%    its nullness annotations.
% \end{enumerate}


The Checker Framework may issue more or fewer errors than another tool.
This is expected, since each tool uses a different analysis.  Remember that
the Checker Framework aims at soundness:  it aims to never miss a possible
null dereference, while at the same time limiting false reports.  Also,
note FindBugs's non-standard meaning for \<@Nullable>
(Section~\ref{findbugs-nullable}).

Java permits you to import at most one annotation of a given name.  For
example, if you use both \<android.annotation.NonNull> and
\<lombok.NonNull> in your source code, then you must write at least one of
them in fully-qualified form, as \<@android.annotation.NonNull> rather than
as \<@NonNull>.


\subsectionAndLabel{Which tool is right for you?}{choosing-nullness-tool}

Different tools are appropriate in different circumstances.  Here is a
brief comparison with FindBugs, but similar points apply to other tools.
(For example, the \href{https://github.com/uber/NullAway}{NullAway} and
\href{https://fbinfer.com/docs/eradicate.html}{Eradicate} tools are more
like sound type-checking than FindBugs, but all of those tools accept
unsoundness --- that is, false negatives or missed warnings --- in exchange
for analysis speed.)

The Checker Framework has a more powerful nullness analysis; FindBugs misses
some real
errors.  FindBugs requires you to annotate your code, but usually not as
thoroughly as the Checker Framework does.  Depending on the importance of
your code, you may desire:  no nullness checking, the cursory checking of
FindBugs, or the thorough checking of the Checker Framework.  You might
even want to ensure that both tools run, for example if your coworkers or
some other organization are still using FindBugs.  If you know that you
will eventually want to use the Checker Framework, there is no point using
FindBugs first; it is easier to go straight to using the Checker Framework.

FindBugs can find other errors in addition to nullness errors; here
we focus on its nullness checks.  Even if you use FindBugs for its other
features, you may want to use the Checker Framework for analyses that can
be expressed as pluggable type-checking, such as detecting nullness errors.

Regardless of whether you wish to use the FindBugs nullness analysis, you
may continue running all of the other FindBugs analyses at the same time as
the Checker Framework; there are no interactions among them.

If FindBugs (or any other tool) discovers a nullness error that the Checker
Framework does not, please report it to us (see
Section~\ref{reporting-bugs}) so that we can enhance the Checker Framework.



\subsectionAndLabel{Incompatibility note about FindBugs \tt{@Nullable}}{findbugs-nullable}

FindBugs has a non-standard definition of \<@Nullable>.  FindBugs's treatment is not
documented in its own
\href{http://findbugs.sourceforge.net/api/edu/umd/cs/findbugs/annotations/Nullable.html}{Javadoc};
it is different from the definition of \<@Nullable> in every other tool for
nullness analysis; it means the same thing as \<@NonNull> when applied to a
formal parameter; and it invariably surprises programmers.  Thus, FindBugs's
\<@Nullable> is detrimental rather than useful as documentation.
In practice, your best bet is to not rely on FindBugs for nullness analysis,
even if you find FindBugs useful for other purposes.

You can skip the rest of this section unless you wish to learn more details.

FindBugs suppresses all warnings at uses of a \<@Nullable> variable.
(You have to use \<@CheckForNull> to
indicate a nullable variable that FindBugs should check.)  For example:

\begin{Verbatim}
     // declare getObject() to possibly return null
     @Nullable Object getObject() { ... }

     void myMethod() {
       @Nullable Object o = getObject();
       // FindBugs issues no warning about calling toString on a possibly-null reference!
       o.toString();
     }
\end{Verbatim}

\noindent
The Checker Framework does not emulate this non-standard behavior of
FindBugs, even if the code uses FindBugs annotations.

With FindBugs, you annotate a declaration, which suppresses checking at
\emph{all} client uses, even the places that you want to check.
It is better to suppress warnings at only the specific client uses
where the value is known to be non-null; the Checker Framework supports
this, if you write \<@SuppressWarnings> at the client uses.
The Checker Framework also supports suppressing checking at all client uses,
by writing a \<@SuppressWarnings> annotation at the declaration site.
Thus, the Checker Framework supports both use cases, whereas FindBugs
supports only one and gives the programmer less flexibility.

In general, the Checker Framework will issue more warnings than FindBugs,
and some of them may be about real bugs in your program.
See Section~\ref{suppressing-warnings-nullness} for information about
suppressing nullness warnings.

(FindBugs made a poor choice of names.  The choice of names should make a
clear distinction between annotations that specify whether a reference is
null, and annotations that suppress false warnings.  The choice of names
should also have been consistent for other tools, and intuitively clear to
programmers.  The FindBugs choices make the FindBugs annotations less
helpful to people, and much less useful for other tools.  As a separate
issue, the FindBugs
analysis is also very imprecise.  For type-related analyses, it is best to
stay away from the FindBugs nullness annotations, and use a more capable
tool like the Checker Framework.)



% As background, here is an explanation of the (sometimes surprising)
% semantics of the FindBugs nullness annotations.
%
%  * edu.umd.cs.findbugs.annotations.NonNull     javax.annotation.Nonnull
%    These mean the obvious thing:   the reference is never null.
%
%  * edu.umd.cs.findbugs.annotations.Nullable     javax.annotation.Nullable
%    This means that the value may be null, but that *all warnings should be
%    suppressed* regarding its use.  In other words, the value is really
%    nullable, but clients should treat it as non-null.  For example:
%
%      // declare getObject() to possibly return null
%      @Nullable Object getObject() { ... }
%
%      // FindBugs issues no warning about calling toString on a possibly-null reference
%      getObject().toString();
%
%    In the Checker Framework, this corresponds to declaring the method
%    return value as @Nullable, then suppressing warnings at client uses
%    that are known to be non-null.  An easy way to suppress the warning
%    is by adding an assert statement about the return value.
%
%    (Alternately, you could declare the method return value as @NonNull, and
%    suppress warnings within the method definition where it returns null,
%    but this approach is not recommended because the @NonNull annotation on
%    the return value would be misleading, and warnings should be suppressed
%    at particular sites where they are known to be unnecessary, not at all
%    call sites whatsoever.)
%
%  * edu.umd.cs.findbugs.annotations.CheckForNull      javax.annotation.CheckForNull
%    This means that the value may be null.  To avoid a NullPointerException,
%    every client should check nullness before dereferencing the value.
%    In the Checker Framework, this corresponds to @Nullable.


\subsectionAndLabel{Relationship to \tt{Optional<T>}}{nullness-vs-optional}

Many null pointer exceptions occur because the programmer forgets to check
whether a reference is null before dereferencing it.  Java 8's
\sunjavadoc{java.base/java/util/Optional.html}{\code{Optional<T>}}
class provides a partial solution:  a programmer must call the \<get> method to
access the value, and the designers of \<Optional> hope that the syntactic
occurrence of the \<get> method will remind programmers to first check that
the value is present.  This is still easy to forget, however.

The Checker Framework contains an Optional Checker (see
Chapter~\ref{optional-checker}) that guarantees that programmers use
\<Optional> correctly, such as calling \<isPresent> before calling \<get>.

There are some limitations to the utility of \code{Optional}, which might
lead to you choose to use regular Java references rather than \<Optional>.
(For more details, see the article
\href{https://homes.cs.washington.edu/~mernst/advice/nothing-is-better-than-optional.html}{``Nothing
  is better than the \<Optional> type''}.)

\begin{itemize}
\item
  It is still possible to call \<get> on a non-present \<Optional>, leading
  to a \code{NoSuchElementException}.  In other words, \code{Optional}
  doesn't solve the underlying problem --- it merely converts a
  \code{NullPointerException} into a \code{NoSuchElementException}
  exception, and in either case your code crashes.
\item
  \code{NullPointerException} is still possible in code that uses \code{Optional}.
\item
  \code{Optional} adds syntactic complexity, making your code longer and harder to
  read.
\item
  \code{Optional} adds time and space overhead.
\item
  \code{Optional} does not address important sources of null pointer
  exceptions, such as partially-initialized objects and calls to \<Map.get>.
\end{itemize}

The Nullness Checker does not suffer these limitations.  Furthermore, it
works with existing code and types, it ensures that you check for null
wherever necessary, and it infers when the check for null is not necessary
based on previous statements in the method.

Java's \<Optional> class provides utility routines to reduce clutter when
using \<Optional>.  The Nullness Checker provides an
\refclass{checker/nullness}{Opt} class that provides all the same methods,
but written for regular possibly-null Java references.


\sectionAndLabel{Initialization Checker}{initialization-checker}

The Initialization Checker determines whether an object is initialized or
not.  For any object that is not fully initialized, the Nullness Checker
treats its fields as possibly-null --- even fields annotated as
\<@NonNull>.

Every object's fields start out as null.  By the time the constructor
finishes executing, the \<@NonNull> fields have been set to a different
value.  Your code can suffer a NullPointerException when using a
\<@NonNull> field, if your code uses the field during initialization.
The Nullness Checker prevents this problem by warning you anytime that you
may be accessing an uninitialized field.  This check is useful because it
prevents errors in your code.  However, the analysis can be confusing to
understand.  If you wish to disable the initialization checks, see
Section~\ref{initialization-checking-suppressing-warnings}.


An object is partially initialized from the time that its constructor starts until its constructor
finishes.  This is relevant to the Nullness Checker because while the
constructor is executing --- that is, before initialization completes ---
a \<@NonNull>
field may be observed to be null, until that field is set.  In
particular, the Nullness Checker issues a warning for code like this:

\begin{Verbatim}
  public class MyClass {
    private @NonNull Object f;
    public MyClass(int x) {
      // Error because constructor contains no assignment to this.f.
      // By the time the constructor exits, f must be initialized to a non-null value.
    }
    public MyClass(int x, int y) {
      // Error because this.f is accessed before f is initialized.
      // At the beginning of the constructor's execution, accessing this.f
      // yields null, even though field f has a non-null type.
      this.f.toString();
      f = new Object();
    }
    public MyClass(int x, int y, int z) {
      m();
      f = new Object();
    }
    public void m() {
      // Error because this.f is accessed before f is initialized,
      // even though the access is not in a constructor.
      // When m is called from the constructor, accessing f yields null,
      // even though field f has a non-null type.
      this.f.toString();
    }
\end{Verbatim}

\noindent
When a field \<f> is declared with a \refqualclass{checker/nullness/qual}{NonNull}
type, then code can depend on the fact that the field is not \<null>.
However, this guarantee does not hold for a partially-initialized object.

The Nullness Checker uses three annotations to indicate whether an object
is initialized (all its \<@NonNull> fields have been assigned), under
initialization (its constructor is currently executing), or its
initialization state is unknown.

These distinctions are mostly relevant within the constructor, or for
references to \code{this} that escape the constructor (say, by being stored
in a field or passed to a method before initialization is complete).
Use of initialization annotations is rare in most code.


\subsectionAndLabel{Initialization qualifiers}{initialization-qualifiers}

\begin{figure}
\includeimage{initialization}{4cm}
\caption{Partial type hierarchy for the Initialization type system.
  \<@UnknownInitialization> and \<@UnderInitialization> each take an
  optional parameter indicating how far initialization has proceeded, and
  the right side of the figure illustrates its type hierarchy in more detail.}
\label{fig-initialization-hierarchy}
\end{figure}

The initialization hierarchy is shown in Figure~\ref{fig-initialization-hierarchy}.
The initialization hierarchy contains these qualifiers:

\begin{description}

\item[\refqualclass{checker/initialization/qual}{Initialized}]
  indicates a type that contains a fully-initialized object.  \code{Initialized}
  is the default, so there is little need for a programmer to write this
  explicitly.

\item[\refqualclass{checker/initialization/qual}{UnknownInitialization}]
  indicates a type that may contain a partially-initialized object.  In a
  partially-initialized object, fields that are annotated as
  \refqualclass{checker/nullness/qual}{NonNull} may be null because the field
  has not yet been assigned.

  \<@UnknownInitialization> takes a parameter that is the class the object
  is definitely initialized up to.  For instance, the type
  \<@UnknownInitialization(Foo.class)> denotes an object in which every
  fields declared in \<Foo> or its superclasses is initialized, but other
  fields might not be.
  Just \<@UnknownInitialization> is equivalent to
  \<@UnknownInitialization(Object.class)>.

\item[\refqualclass{checker/initialization/qual}{UnderInitialization}]
  indicates a type that contains a partially-initialized object that is
  under initialization --- that is, its constructor is currently executing.
  It is otherwise the same as \<@UnknownInitialization>.  Within the
  constructor, \code{this} has
  \refqualclass{checker/initialization/qual}{UnderInitialization} type until
  all the \code{@NonNull} fields have been assigned.

\end{description}

  A partially-initialized object (\code{this} in a constructor) may be
  passed to a helper method or stored in a variable; if so, the method
  receiver, or the field, would have to be annotated as
  \<@UnknownInitialization> or as \<@UnderInitialization>.

% However, if the constructor makes
% a method call (passing \code{this} as a parameter or the receiver), then
% the called method could observe the object in an illegal state.

If a reference has
\code{@UnknownInitialization} or \code{@UnderInitialization} type, then all of its \code{@NonNull} fields are treated as
\refqualclass{checker/nullness/qual}{MonotonicNonNull}:  when read, they are
treated as being \refqualclass{checker/nullness/qual}{Nullable}, but when
written, they are treated as being
\refqualclass{checker/nullness/qual}{NonNull}.

\begin{sloppypar}
The initialization hierarchy is orthogonal to the nullness hierarchy.  It
is legal for a reference to be \<@NonNull @UnderInitialization>, \<@Nullable @UnderInitialization>,
\<@NonNull @Initialized>, or \<@Nullable @Initialized>.  The nullness hierarchy tells
you about the reference itself:  might the reference be null?  The initialization
hierarchy tells you about the \<@NonNull> fields in the referred-to object:
might those fields be temporarily null in contravention of their
type annotation?
% It's a figure rather than appearing inline so as not to span page breaks
% in the printed manual.
Figure~\ref{fig-initialization-examples} contains some examples.
\end{sloppypar}

\begin{figure}
\begin{tabular}{l|l|l}
Declarations & Expression & Expression's nullness type, or checker error \\ \hline
\begin{minipage}{1.5in}
\begin{Verbatim}
class C {
  @NonNull Object f;
  @Nullable Object g;
  ...
}
\end{Verbatim}
\end{minipage} & & \\ \cline{2-3}
\<@NonNull @Initialized C a;>
& \<a> & \<@NonNull> \\
& \<a.f> & \<@NonNull> \\
& \<a.g> & \<@Nullable> \\ \cline{2-3}
\<@NonNull @UnderInitialization C b;>
& \<b> & \<@NonNull> \\
& \<b.f> & \<@MonotonicNonNull> \\
& \<b.g> & \<@Nullable> \\ \cline{2-3}
\<@Nullable @Initialized C c;>
& \<c> & \<@Nullable> \\
& \<c.f> & error: deref of nullable \\
& \<c.g> & error: deref of nullable \\ \cline{2-3}
\<@Nullable @UnderInitialization C d;>
& \<d> & \<@Nullable> \\
& \<d.f> & error: deref of nullable \\
& \<d.g> & error: deref of nullable \\
\end{tabular}
\caption{Examples of the interaction between nullness and initialization.
  Declarations are shown at the left for reference, but the focus of the
  table is the expressions and their nullness type or error.}
\label{fig-initialization-examples}
\end{figure}


% Does our implementation handle static fields soundly?  NO!  See issue
% #105.  Maybe document this?


\subsectionAndLabel{How an object becomes initialized}{becoming-initialized}

Within the constructor,
\code{this} starts out with \refqualclass{checker/initialization/qual}{UnderInitialization} type.
As soon as all of the \refqualclass{checker/nullness/qual}{NonNull} fields
in class $C$ have been initialized, then \code{this} is treated as
\refqualclass{checker/initialization/qual}{UnderInitialization}\code{(\emph{C})}.
This means that \code{this} is still being initialized, but all
initialization of $C$'s fields is complete, including all fields of supertypes.
Eventually, when all constructors complete, the type is
\refqualclass{checker/initialization/qual}{Initialized}.

The Initialization Checker issues an error if the constructor fails to initialize
any \code{@NonNull} field.  This ensures that the object is in a legal (initialized)
state by the time that the constructor exits.
This is different than Java's test for definite assignment (see
\href{https://docs.oracle.com/javase/specs/jls/se11/html/jls-16.html}{JLS ch.16}),
% , which requires that local
% variables (and blank \code{final} fields) must be assigned.  Java does not
% require that non-\code{final} fields be assigned, since
which does not apply to fields (except blank final ones, defined in
\href{https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.12.4}{JLS \S 4.12.4}) because fields
have a default value of null.


All \code{@NonNull} fields must either have a
default in the field declaration, or be assigned in the constructor or in a
helper method that the constructor calls.  If
your code initializes (some) fields in a helper method, you will need to
annotate the helper method with an annotation such as
\refqualclass{checker/nullness/qual}{EnsuresNonNull}\code{(\{"field1", "field2"\})}
for all the fields that the helper method assigns.

% TODO:
% We need an
%   @EnsuresInitialized("b")
% that is analogous to
%   @EnsuresNonNull("b")
% when we are dealing with a field of primitive type.
% But, for now just use the same annotation, @EnsuresNonNull, for both purposes.


\subsectionAndLabel{\code{@UnderInitialization} examples}{underinitialization-examples}

The most common use for the \<@UnderInitialization> annotation is for a
helper routine that is called by constructor.  For example:

\begin{Verbatim}
  class MyClass {
    Object field1;
    Object field2;
    Object field3;

    public MyClass(String arg1) {
      this.field1 = arg1;
      init_other_fields();
    }

    // A helper routine that initializes all the fields other than field1.
    @EnsuresNonNull({"field2", "field3"})
    private void init_other_fields(@UnderInitialization(Object.class) MyClass this) {
      field2 = new Object();
      field3 = new Object();
    }

    public MyClass(String arg1, String arg2, String arg3) {
      this.field1 = arg1;
      this.field2 = arg2;
      this.field3 = arg3;
      checkRep();
    }

    // Verify that the representation invariants are satisfied.
    // Works as long as the MyClass fields are initialized, even if the receiver's
    // class is a subclass of MyClass and not all of the subclass fields are initialized.
    private void checkRep(@UnderInitialization(MyClass.class) MyClass this) {
      ...
    }


  }
\end{Verbatim}

% Most readers can
% skip this section on first reading; you can return to it once you have
% mastered the rest of the Nullness Checker.

At the end of the constructor, \<this> is not fully initialized. Rather,
it is \<@UnderInitialization(\emph{CurrentClass.class})>.
The reason is that there might be subclasses with uninitialized fields.
The following example illustrates this:

\begin{Verbatim}
class A {
   @NonNull String a;
   public A() {
       a = "";
       // Now, all fields of A are initialized.
       // However, if this constructor is invoked as part of 'new B()', then
       // the fields of B are not yet initialized.
       // If we would type 'this' as @Initialized, then the following call is valid:
       doSomething();
   }
   void doSomething() {}
}

class B extends A {
   @NonNull String b;
   @Override
   void doSomething() {
       // Dereferencing 'b' is ok, because 'this' is @Initialized and 'b' @NonNull.
       // However, when executing 'new B()', this line throws a null-pointer exception.
       b.toString();
   }
}
\end{Verbatim}


\subsectionAndLabel{Partial initialization}{partial-initialization}

So far, we have discussed initialization as if it is an all-or-nothing property:
an object is non-initialized until initialization completes, and then it is initialized.  The full truth is a bit more complex:  during the
initialization process an object can be partially initialized, and as the
object's superclass constructors complete, its initialization status is updated.  The
Initialization Checker lets you express such properties when necessary.

Consider a simple example:

\begin{Verbatim}
class A {
  Object aField;
  A() {
    aField = new Object();
  }
}
class B extends A {
  Object bField;
  B() {
    super();
    bField = new Object();
  }
}
\end{Verbatim}

Consider what happens during execution of \<new B()>.

\begin{enumerate}
\item \<B>'s constructor begins to execute.  At this point, neither the
  fields of \<A> nor those of \<B> have been initialized yet.
\item \<B>'s constructor calls \<A>'s constructor, which begins to execute.
  No fields of \<A> nor of \<B> have been initialized yet.
\item \<A>'s constructor completes.  Now, all the fields of \<A> have been
  initialized, and their invariants (such as that field \<a> is non-null) can be
  depended on.  However, because \<B>'s constructor has not yet completed
  executing, the object being constructed is not yet fully initialized.
  When treated as an \<A> (e.g., if only the \<A> fields are accessed), the
  object is initialized, but when treated as a \<B>, the object
  is still non-initialized.
\item \<B>'s constructor completes.  The object is initialized when treated
  as an \<A> or a \<B>.  (And, the object is fully initialized
   if \<B>'s constructor was invoked via a \<new B()>.  But the type system
   cannot assume that --- there might be a \<class C extends B \{
  ... \}>, and \<B>'s constructor might have been invoked from that.)
\end{enumerate}

At any moment during initialization, the superclasses of a given class
can be divided into those that have completed initialization and those that
have not yet completed initialization.  More precisely, at any moment there
is a point in the class hierarchy such that all the classes above that
point are fully initialized, and all those below it are not yet
initialized.  As initialization proceeds, this dividing line between the
initialized and uninitialized classes moves down the type hierarchy.

The Nullness Checker lets you indicate where the dividing line is between
the initialized and non-initialized classes.
The \<@UnderInitialization(\emph{classliteral})>
indicates the first class that is known to be fully initialized.
When you write \refqualclass{checker/initialization/qual}{UnderInitialization}\code{(OtherClass.class) MyClass x;}, that
means that variable \<x> is initialized for \<OtherClass> and its
superclasses, and \<x> is (possibly) uninitialized for \<MyClass> and all subclasses.

The example above lists 4 moments during construction.  At those moments,
the type of the object being constructed is:

\begin{enumerate}
\item
  \<@UnderInitialization B>
\item
  \<@UnderInitialization A>
\item
  \<@UnderInitialization(A.class) A>
  %% Not quite equivalent because the Java (non-qualified) type differs
  % ; equivalently, \<@UnderInitialization B>
\item
  \<@UnderInitialization(B.class) B>
\end{enumerate}


\subsectionAndLabel{Method calls from the constructor}{initialization-constructor}

Consider the following incorrect program.

\begin{Verbatim}
class A {
  Object aField;
  A() {
    aField = new Object();
    process(5);  // illegal call
  }
  public void process(int arg) { ... }
}
\end{Verbatim}

The call to \<process()> is not legal.
\<process()> is declared to be called on a fully-initialized receiver, which is
the default if you do not write a different initialization annotation.
At the call to \<process()>, all the fields of \<A> have been set,
but \<this> is not fully initialized because fields in subclasses of \<A> have
not yet been set.  The type of \<this> is \<@UnderInitialization(A.class)>,
meaning that \<this> is partially-initialized, with the \<A> part of
initialization done but the initialization of subclasses not yet complete.

The Initialization Checker output indicates this problem:

\begin{Verbatim}
Client.java:7: error: [method.invocation.invalid] call to process(int) not allowed on the given receiver.
    process(5);  // illegal call
           ^
  found   : @UnderInitialization(A.class) A
  required: @Initialized A
\end{Verbatim}

Here is a subclass and client code that crashes with a \<NullPointerException>.

\begin{Verbatim}
class B extends A {
  List<Integer> processed;
  B() {
    super();
    processed = new ArrayList<Integer>();
  }
  @Override
  public void process(int arg) {
    super();
    processed.add(arg);
  }
}
class Client {
  public static void main(String[] args) {
    new B();
  }
}
\end{Verbatim}

You can correct the problem in multiple ways.

One solution is to not call methods that can be overridden from the
constructor:  move the call to \<process()> to after the constructor has
completed.

Another solution is to change the declaration of \<process()>:

\begin{Verbatim}
  public void process(@UnderInitialization(A.class) A this, int arg) { ... }
\end{Verbatim}

If you choose this solution, you will need to rewrite the definition of
\<B.process()> so that it is consistent with the declared receiver type.

A non-solution is to prevent subclasses from overriding \<process()> by
using \<final> on the method.  This doesn't work because even if
\<process()> is not overridden, it might call other methods that are
overridden.

As final classes cannot have subclasses, they can be handled more
flexibly: once all fields of the final class have been
initialized, \<this> is fully initialized.

% TODO: One could imagine having an annotation indicating that the routine
% is "truly final":  it is final and it never calls, directly, or
% indirectly, any routine that might be overridden.  I'm not sure how you
% would confirm that, given the existence of callbacks from other code.



\subsectionAndLabel{Initialization of circular data structures}{circular-initialization}

There is one final aspect of the initialization type system to be
considered:  the rules governing reading and writing to objects that are
currently under initialization (both reading from fields of objects under
initialization, as well as writing objects under initialization to fields).
By default, only fully-initialized objects can be stored in a field of
another object.  If this was the only option, then it would not be possible
to create circular data structures (such as a doubly-linked list) where
fields have a \refqualclass{checker/nullness/qual}{NonNull} type.  However,
the annotation
\refqualclass{checker/initialization/qual}{NotOnlyInitialized} can be used to
indicate that a field can store objects that are currently under initialization.
In this case, the rules for reading and writing to that field become a little
bit more interesting, to soundly support circular structures.

The rules for reading from a
\refqualclass{checker/initialization/qual}{NotOnlyInitialized} field
are summarized in Figure~\ref{fig-init-read-field}.  Essentially, nothing is
known about the initialization status of the value returned unless the receiver
was \refqualclass{checker/initialization/qual}{Initialized}.

\begin{figure}
\centering
\begin{tabular}{l|l|l}
  \<x.f>&\<f> is \<@NonNull>& \<f> is \<@Nullable>\\ \hline
  \<x> is \<@Initialized> & \<@Initialized @NonNull> & \<@Initialized @Nullable> \\
  \<x> is \<@UnderInitialization> & \<@UnknownInitialization @Nullable> & \<@UnknownInitialization @Nullable> \\
  \<x> is \<@UnknownInitialization> & \<@UnknownInitialization @Nullable> & \<@UnknownInitialization @Nullable> \\
\end{tabular}
\caption{Initialization rules for reading a \refqualclass{checker/initialization/qual}{NotOnlyInitialized} field \<f>.}
\label{fig-init-read-field}
\end{figure}

Similarly, Figure~\ref{fig-init-write-field} shows under which conditions
an assignment \<x.f = y> is allowed for a
\refqualclass{checker/initialization/qual}{NotOnlyInitialized} field \<f>.
If the receiver \<x> is
\refqualclass{checker/initialization/qual}{UnderInitialization}, then any
\<y> can be of any initialization state.  If \<y> is known to be
fully initialized, then any receiver is allowed.  All other assignments
are disallowed.

\begin{figure}
\centering
\begin{tabular}{l|ccc}
  \<x.f = y>&\<y> is \<@Initialized>& \<y> is \<@UnderInitialization>& \<y> is \<@UnknownInitialization>\\ \hline
  \<x> is \<@Initialized> & yes & no & no \\
  \<x> is \<@UnderInitialization> & yes & yes & yes \\
  \<x> is \<@UnknownInitialization> & yes & no & no \\
\end{tabular}
\caption{Rules for deciding when an assignment \<x.f = y> is allowed for a
\refqualclass{checker/initialization/qual}{NotOnlyInitialized} field \<f>.}
\label{fig-init-write-field}
\end{figure}

These rules allow for the safe initialization of circular structures.  For instance,
consider a doubly linked list:

\begin{Verbatim}
  class List<T> {
    @NotOnlyInitialized
    Node<T> sentinel;

    public List() {
      this.sentinel = new Node<>(this);
    }

    void insert(@Nullable T data) {
      this.sentinel.insertAfter(data);
    }

    public static void main() {
      List<Integer> l = new List<>();
      l.insert(1);
      l.insert(2);
    }
  }

  class Node<T> {
    @NotOnlyInitialized
    Node<T> prev;

    @NotOnlyInitialized
    Node<T> next;

    @NotOnlyInitialized
    List parent;

    @Nullable
    T data;

    // for sentinel construction
    Node(@UnderInitialization List parent) {
      this.parent = parent;
      this.prev = this;
      this.next = this;
    }

    // for data node construction
    Node(Node<T> prev, Node<T> next, @Nullable T data) {
      this.parent = prev.parent;
      this.prev = prev;
      this.next = next;
      this.data = data;
    }

    void insertAfter(@Nullable T data) {
      Node<T> n = new Node<>(this, this.next, data);
      this.next.prev = n;
      this.next = n;
    }
  }
\end{Verbatim}

% \paragraphAndLabel{Example}{initialization-example}
%
% As another example, consider the following 12 declarations, where class A
% extends Object and class B extends A:
%
% \begin{Verbatim}
%     @UnderInitialization(Object.class) Object uOo;
%     @Initialized Object o;
%
%     @UnderInitialization(Object.class) A uOa;
%     @UnderInitialization(A.class) A uAa;
%     @Initialized A nraA;
%
%     @UnderInitialization(Object.class) B uOb;
%     @UnderInitialization(A.class) B uAb;
%     @UnderInitialization(B.class) B uBb;
%     @Initialized B b;
% \end{Verbatim}
%
% In the following table, the type in cell C1 is a supertype of the type in
% cell C2 if:  C1 is at least as high and at least as far left in the table
% as C2 is.  For example, \<nraA>'s type is a supertype of those of \<rB>,
% \<nraB>, \<nrbB>, \<a>, and \<b>.  (The empty cells on the top row are real
% types, but are not expressible.  The other empty cells are not interesting
% types.)
%
% \noindent
% \begin{tabular}{|c|c|c|}
%
% \hline
%     \<@UnderInitialization Object rO;>
% &
% &
% \\
% \hline
%
%     \<@Initialized(Object.class) Object nroO;>
% &
% \begin{minipage}{2in}
% \begin{Verbatim}
% @UnderInitialization A rA;
% @Initialized(Object.class) A nroA;
% \end{Verbatim}
% \end{minipage}
% &
%     \<@Initialized(Object.class) B nroB;>
% \\
% \hline
%
% &
%     \<@Initialized(A.class) A nraA;>
% &
% \begin{minipage}{1.75in}
% \begin{Verbatim}
% @UnderInitialization B rB;
% @Initialized(A.class) B nraB;
% \end{Verbatim}
% \end{minipage}
% \\
% \hline
%
% &
% &
%     \<@Initialized(B.class) B nrbB;>
% \\
% \hline
%
%     \<Object o;>
% &
%     \<A a;>
% &
%     \<B b;>
% \\
% \hline
% \end{tabular}



% \urldef{\jlsconstructorbodyurl}{\url}{https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.8.7}
% (Recall that the superclass constructor is called on the first line, or is
% inserted automatically by the compiler before the first line, see
% \href{\jlsconstructorbodyurl}{JLS \S8.8.7}.)



\subsectionAndLabel{How to handle warnings}{initialization-warnings}


\subsubsectionAndLabel{``error:  the constructor does not initialize fields: \ldots''}{initialization-warnings-constructor}

Like any warning, ``error:  the constructor does not initialize fields:
\ldots'' indicates that either your annotations are incorrect or your code
is buggy.  You can fix either the annotations or the code.

\begin{itemize}
\item
  Declare the field as \refqualclass{checker/nullness/qual}{Nullable}.  Recall
  that if you did not write an annotation, the field defaults to
  \refqualclass{checker/nullness/qual}{NonNull}.
\item
  Declare the field as \refqualclass{checker/nullness/qual}{MonotonicNonNull}.
  This is appropriate if the field starts out as \<null> but is later set
  to a non-null value.  You may then wish to use the
  \refqualclass{checker/nullness/qual}{EnsuresNonNull} annotation to indicate
  which methods set the field, and the
  \refqualclass{checker/nullness/qual}{RequiresNonNull} annotation to indicate
  which methods require the field to be non-null.
\item
  Initialize the field in the constructor or in the field's initializer, if
  the field should be initialized.  (In this case, the Initialization
  Checker has found a bug!)

  Do \emph{not} initialize the field to an arbitrary non-null value just to
  eliminate the warning.  Doing so degrades your code:  it introduces a
  value that will confuse other programmers, and it converts a clear
  NullPointerException into a more obscure error.
\end{itemize}

\subsubsectionAndLabel{``call to \ldots\ is not allowed on the given receiver''}{initialization-warnings-receiver}

If your code calls an instance method from a constructor, you may see a
message such as the following:

\begin{Verbatim}
MyFile.java:123: error: call to initHelper() not allowed on the given receiver.
    initHelper();
              ^
  found   : @UnderInitialization(com.google.Bar.class) @NonNull MyClass
  required: @Initialized @NonNull MyClass
\end{Verbatim}

The problem is that the current object (\<this>) is under initialization,
but the receiver formal parameter (Section~\ref{faq-receiver}) of method
\<initHelper()> is implicitly annotated as
\refqualclass{checker/initialization/qual}{Initialized}.  If
\<initHelper()> doesn't depend on its receiver being initialized --- that
is, it's OK to call \<x.initHelper> even if \<x> is not initialized ---
then you can indicate that by using
\refqualclass{checker/initialization/qual}{UnderInitialization} or
\refqualclass{checker/initialization/qual}{UnknownInitialization}.

\begin{Verbatim}
class MyClass {
  void initHelper(@UnknownInitialization MyClass this, String param1) { ... }
}
\end{Verbatim}

\noindent
You are likely to want to annotate \<initHelper()> with
\refqualclass{checker/nullness/qual}{EnsuresNonNull} as well; see
Section~\ref{nullness-method-annotations}.

You may get the ``call to \ldots\ is not allowed on the given receiver''
error even if your constructor has already initialized all the fields.
For this code:

\begin{Verbatim}
public class MyClass {
  @NonNull Object field;
  public MyClass() {
    field = new Object();
    helperMethod();
  }
  private void helperMethod() {
  }
}
\end{Verbatim}

\noindent
the Nullness Checker issues the following warning:

\begin{Verbatim}
MyClass.java:7: error: call to helperMethod() not allowed on the given receiver.
    helperMethod();
                ^
  found   : @UnderInitialization(MyClass.class) @NonNull MyClass
  required: @Initialized @NonNull MyClass
1 error
\end{Verbatim}

\begin{sloppypar}
The reason is that even though the object under construction has had all
the fields declared in \<MyClass> initialized, there might be a subclass of
\<MyClass>.  Thus, the receiver of \<helperMethod> should be declared as
\<@UnderInitialization(MyClass.class)>, which says that initialization has
completed for all the \<MyClass> fields but may not have been completed
overall.  If \<helperMethod> had been a public method that could also be called after
initialization was actually complete, then the receiver should have type
\<@UnknownInitialization>, which is the supertype of
\<@UnknownInitialization> and \<@UnderInitialization>.
\end{sloppypar}


\subsectionAndLabel{Suppressing warnings}{initialization-checking-suppressing-warnings}

To suppress most warnings related to partially-initialized values, use the
``initialization.''~(note the trailing period) warning suppression key.  You
can write \<@SuppressWarnings("initialization.")> on a field, constructor, or
class, or pass the command-line argument
\<-AsuppressWarnings=initialization.>~when running the Nullness Checker.
(For more about suppressing warnings, see
\chapterpageref{suppressing-warnings}).  You will no longer get a guarantee
of no null pointer exceptions, but you can still use the Nullness Checker
to find most of the null pointer problems in your code.

This suppresses warnings that are specific to the Initialization Checker,
but does not suppress warnings issued by the Checker Framework itself, such
as about assignments or method overriding.

It is not possible to completely disable initialization checking while
retaining nullness checking.  The ``initialization'' warning suppression
key (without a period) has the same effect as the ``nullness'' key:  both
of them disable all nullness and initialization checking.  That is because
of an implementation detail of the Nullness and Initialization Checkers:
they are actually the same checker, rather than being two separate checkers
that are aggregated together.


\subsectionAndLabel{More details about initialization checking}{initialization-checking}


\paragraphAndLabel{Use of method annotations}{initialization-checking-method-annotations}

A method with a non-initialized receiver may assume that a few fields (but not all
of them) are non-null, and it sometimes sets some more fields to non-null
values.  To express these concepts, use the
\refqualclass{checker/nullness/qual}{RequiresNonNull},
\refqualclass{checker/nullness/qual}{EnsuresNonNull}, and
\refqualclass{checker/nullness/qual}{EnsuresNonNullIf} method annotations;
see Section~\ref{nullness-method-annotations}.


\paragraphAndLabel{Source of the type system}{initialization-checking-type-system}

The type system enforced by the Initialization Checker is known as
``Freedom Before Commitment''~\cite{SummersM2011}.  Our implementation
changes its initialization modifiers (``committed'', ``free'', and
``unclassified'') to ``initialized'', ``unknown initialization'', and
``under initialization''.  Our implementation also has several
enhancements.  For example, it supports partial initialization (the
argument to the \<@UnknownInitialization> and \<@UnderInitialization>
annotations).



% LocalWords:  NonNull plugin quals un NonNullExampleWithWarnings java ahndrich
% LocalWords:  NotNull IntelliJ FindBugs Nullable TODO Alint nullable NNEL JSR
% LocalWords:  DefaultLocation Nullness PolyNull nullness AnnotateNullable JLS
% LocalWords:  Daikon JastAdd javac DefaultQualifier boolean MyEnumType NonRaw
% LocalWords:  NullnessAnnotatedTypeFactory NullnessVisitor MonotonicNonNull
% LocalWords:  inferencer Nonnull CheckForNull UnknownNullness rawtypes de ch
% LocalWords:  castNonNull NullnessUtil assertNotNull codebases checkNotNull
% LocalWords:  Nullability typeargs nulltest EnsuresNonNullIf listFiles faq
% LocalWords:  isDirectory AssertionError intraprocedurally SuppressWarnings rB
% LocalWords:  FindBugs's getObject RequiresNonNull EnsuresNonNull KeyFor
% LocalWords:  nonnull EnsuresNonNull arg orElse isPresent bField qual ccc
% LocalWords:  keySet getField keyfor param TypeName containsValue indexOf nraA
% LocalWords:  lastIndexOf deref getProperty getProperties classliteral MyClass
% LocalWords:  typeofthis nraB nrbB rO nroO nroB containsKey enum NullAway
% LocalWords:  JUnit's field1 field2 superclasses Foo C1 C2 PolyRaw
% LocalWords:  NullnessChecker redundantNullComparison instanceof runtime
% LocalWords:  noInitForMonotonicNonNull UnknownInitialization isArray
% LocalWords:  UnderInitialization getComponentType AsuppressWarnings
% LocalWords:  isEmpty AssumeAssertion cleanroom varargs OtherClass
% LocalWords:  mymap mykey KeyType ValueType
% LocalWords:  dereferenced dereference Dereferencing initializers
% LocalWords:  initHelper helperMethod NoSuchElementException classpath
% LocalWords:  soundArrayCreationNullness lombok findbugs CurrentClass
% LocalWords:  NotOnlyInitialized underinitialization