<<

APPENDIX

Character Encodings

A is the basic unit of a writing , for example, a of the English , and an ideograph of an ideographic such as Chinese and Japanese ideographs. In the written form, a character is identified by its shape, also known as . The identification of a character with its shape is not precise. It depends on many factors, for example, a is identified as a minus sign in a mathematical expression; some Greek and Latin letters have the same shapes, but they are considered different characters in two written scripts. understand only numbers, more precisely, only 0 and 1. Therefore, it was necessary convert, with the advent of computers, the characters into (or combinations) inside the ’s memory, that the text ( of characters) could be stored and reproduced. However, different computers may represent different characters with the same bit combinations, which may lead to misinterpretation of text stored by one computer system and reproduced by another. Therefore, for correct exchange of between two computer systems, it is necessary that one computer system understand unambiguously the coded form of the characters represented in bit combinations produced by another computer system and vice versa. Before begin our discussion of some widely used character encodings, it is necessary to understand some commonly used terms. • An abstract character is a unit of textual information, for example, the Latin capital letter A (‘A’). • A character repertoire is defined as the of characters to be encoded. A character repertoire can be fixed or open. In a fixed character repertoire, once the set of characters to be encoded is decided, it is never changed. ASCII and POSIX portable character repertoires are examples of fixed character repertoires. In an open character repertoire, a new character may be added any time. and Windows Western European repertoires are examples of open character repertoires. The currency sign and Indian Rupee sign were added to Unicode because it is an open repertoire. • A coded character set is defined as a mapping from a set of non-negative (also known as positions, code points, code values, character numbers, and code ) to a set of abstract characters. The that maps to a character is called the code for that character and the character is called an encoded character. A coded character set is also called a , coded character repertoire, character set definition, or . Figure A-1 depicts two different coded character sets; both of them have the same character repertoire, which is the set of three characters (A, B, and ) and the same code points, which is the set of three non-negative integers (1, 2, and 3).

© Kishori Sharan 2017 985 K. Sharan, Beginning Java 9 Fundamentals, https://doi.org/10.1007/978-1-4842-2902-6 APPENDIX a ■ Character Encodings

Figure A-1. Two coded character sets having the same character repertoire and code points

To define a coded character set, you need to specify three things: • A set of code points • A set of characters • A mapping between the set of code points and the set of characters The number of bits used to represent a character determines how many distinct characters can be represented in a coded character set. Some widely used coded character sets are outlined in the following sections.

ASCII ASCII, the American Standard Code for Information Interchange, is a 7-bit coded character set. ASCII has 27 (=128) code points and so it represents 128 distinct characters whose numeric values range from 0 (binary 0000000) to 127 (binary 1111111). The characters NUL and DELETE are represented by code points 0000000 and 1111111, respectively. There are historical reasons to assign these code points to NUL and DELETE characters. It was common to use punched paper tapes to store data for processing by the time ASCII was developed. A 1 bit was used to represent a hole on the paper tape, whereas a 0 bit represented the absence of a hole. Since a row of seven 0 bits would be indistinguishable from blank tape, the coding 0000000 would have to represent a NUL character, that is, the absence of any effect. Since holes, once punched, could not be erased but an erroneous character could always be converted into 111111, this bit pattern was adopted as the . ASCII uses the first 32 bit combinations (or code points) to represent control characters. This range includes the NUL character, but not the DELETE character. Therefore, it leaves 95 bit combinations for printing characters.

128(All characters) - 32(Control Characters) - 1(DELETE) = 95(Printing characters)

All printing characters are arranged in the order that could be used for sorting purposes. The SPACE character is normally sorted before any other printing character. Therefore, the SPACE character is allocated the first position among the printing characters. The for the SPACE character in ASCII is 32, or 1100000. The code point range of 48 to 57 represents 0 to 9 digits, 65 to 90 represents 26 uppercase letters A to Z, and 97 to 122 represents 26 lowercase letters a to z. Modern computers use an 8-bit combination, also known as a , as the smallest unit for storage. Therefore, on modern computers, a 7-bit ASCII character uses 8 bits (or 1 byte) of memory, of which the most significant bit is always set to 0; for example, SPACE is stored as 01100000 and DELETE is stored as 0111111. Table A-1 contains the list of characters in the ASCII character set.

986 APPENDIX a ■ Character Encodings

Table A-1. ASCII Character Set Decimal Binary Character Official Name

0 0 0 NUL NULL 1 1 1 SOH Start of heading 2 2 10 STX Start of text 3 3 11 ETX End of text 4 4 100 EOT End of transmission 5 5 101 ENQ Enquiry 6 6 110 ACK Acknowledge 7 7 111 BEL Bell 8 8 1000 BS 9 9 1001 TAB Horizontal tab 10 0A 1010 LF Line feed (new line) 11 0B 1011 VT Vertical tab 12 0C 1100 FF Form feed (new page) 13 0D 1101 CR 14 0E 1110 SO Shift out 15 0F 1111 SI Shift in 16 10 10000 DLE Data link escape 17 11 10001 DC1 Device control 1 18 12 10010 DC2 Device control 2 19 13 10011 DC3 Device control 3 20 14 10100 DC4 Device control 4 21 15 10101 NAK Negative acknowledge 22 16 10110 SYN Synchronous idle 23 17 10111 ETB End of transmission 24 18 11000 CAN Cancel 25 19 11001 End of medium 26 1A 11010 SUB Substitute 27 1B 11011 ESC Escape 28 1C 11100 FS File separator 29 1D 11101 GS Group separator 30 1E 11110 RS Record separator 31 1F 11111 US Unit separator 32 20 100000 SP Space 33 21 100001 ! (continued)

987 APPENDIX a ■ Character Encodings

Table A-1. (continued) Decimal Hexadecimal Binary Character Official Name 34 22 100010 " 35 23 100011 # 36 24 100100 $ 37 25 100101 % 38 26 100110 & 39 27 100111 ' 40 28 101000 ( Left parenthesis 41 29 101001 ) Right parenthesis 42 2A 101010 * 43 2B 101011 + Plus sign 44 2C 101100 , 45 2D 101101 - Hyphen/minus 46 2E 101110 . Full stop/period 47 2F 101111 / Solidus/slash 48 30 110000 0 Digit zero 49 31 110001 1 Digit one 50 32 110010 2 Digit two 51 33 110011 3 Digit three 52 34 110100 4 Digit four 53 35 110101 5 Digit five 54 36 110110 6 Digit six 55 37 110111 7 Digit seven 56 38 111000 8 Digit eight 57 39 111001 9 Digit nine 58 3A 111010 : Colon 59 3B 111011 ; 60 3C 111100 < Less-than sign 61 3D 111101 = Equals sign 62 3E 111110 > Greater-than sign 63 3F 111111 ? 64 40 1000000 @ Commercial at 65 41 1000001 A Latin capital letter A 66 42 1000010 B Latin capital letter B (continued)

988 APPENDIX a ■ Character Encodings

Table A-1. (continued) Decimal Hexadecimal Binary Character Official Name 67 43 1000011 C Latin capital letter C 68 44 1000100 D Latin capital letter D 69 45 1000101 Latin capital letter E 70 46 1000110 F Latin capital letter F 71 47 1000111 G Latin capital letter G 72 48 1001000 H Latin capital letter H 73 49 1001001 Latin capital letter I 74 4A 1001010 J Latin capital letter J 75 4B 1001011 K Latin capital letter K 76 4C 1001100 L Latin capital letter L 77 4D 1001101 M Latin capital letter M 78 4E 1001110 Latin capital letter N 79 4F 1001111 Latin capital letter O 80 50 1010000 P Latin capital letter P 81 51 1010001 Q Latin capital letter Q 82 52 1010010 R Latin capital letter R 83 53 1010011 S Latin capital letter S 84 54 1010100 T Latin capital letter T 85 55 1010101 Latin capital letter U 86 56 1010110 V Latin capital letter V 87 57 1010111 W Latin capital letter W 88 58 1011000 X Latin capital letter X 89 59 1011001 Y Latin capital letter Y 90 5A 1011010 Z Latin capital letter Z 91 5B 1011011 [ Left square bracket/opening square bracket 92 5C 1011100 \ Reverse solidus/ 93 5D 1011101 ] Right square bracket/closing square bracket 94 5E 1011110 ^ Circumflex accent 95 5F 1011111 _ Low line/spacing 96 60 1100000 ` Grave accent 97 61 1100001 A Latin small letter A 98 62 1100010 B Latin small letter B 99 63 1100011 C Latin small letter C (continued)

989 APPENDIX a ■ Character Encodings

Table A-1. (continued) Decimal Hexadecimal Binary Character Official Name 100 64 1100100 D Latin small letter D 101 65 1100101 E Latin small letter E 102 66 1100110 F Latin small letter F 103 67 1100111 G Latin small letter G 104 68 1101000 H Latin small letter H 105 69 1101001 I Latin small letter I 106 6A 1101010 J Latin small letter J 107 6B 1101011 K Latin small letter K 108 6C 1101100 L Latin small letter L 109 6D 1101101 M Latin small letter M 110 6E 1101110 N Latin small letter N 111 6F 1101111 O Latin small letter O 112 70 1110000 P Latin small letter P 113 71 1110001 Q Latin small letter Q 114 72 1110010 R Latin small letter R 115 73 1110011 S Latin small letter S 116 74 1110100 T Latin small letter T 117 75 1110101 U Latin small letter U 118 76 1110110 V Latin small letter V 119 77 1110111 W Latin small letter W 120 78 1111000 X Latin small letter X 121 79 1111001 Y Latin small letter Y 122 7A 1111010 Z Latin small letter Z 123 7B 1111011 { Left curly bracket/opening curly bracket 124 7C 1111100 | Vertical line/ 125 7D 1111101 } Right curly bracket/closing curly bracket 126 7E 1111110 ~ 127 7F 1111111 DEL DELETE

8-Bit Character Sets The ASCII character set worked fine for the English language. Representing the from other languages, for example, French and German, led to the development of an 8-bit character set. An 8-bit character set defines 28 (or 256) character positions whose numeric values range from 0 to 255. The bit combination for an 8-bit character set ranges from 00000000 to 11111111. The 8-bit character set is divided into two parts. The first part represents characters, which are the same as in the ASCII character set. The second part introduces 128 new characters. The first 32 positions in the second part are reserved for control

990 APPENDIX a ■ Character Encodings characters. Therefore, there are two areas in an 8-bit character set: 0-31 and 128-159. Since the SPACE and DELETE characters are already defined in the first part, an 8-bit character set can accommodate 192 printing characters (95 + 97), including SPACE. ISO Latin-1 is one example of an 8-bit character set. Even an 8-bit character set is not large enough to accommodate most of the alphabets of all languages in the world. This lead to the development of a bigger (may be the biggest) character set, which is known as the Universal Character Set (UCS).

Universal Multiple- Coded Character Set (UCS) The Universal Multiple-Octet Coded Character Set, simply known as UCS, is intended to provide a single coded character set for the encoding of written forms of all the languages of the world and of a wide range of additional symbols that may be used in conjunction with such languages. It is intended not only to cover languages in current use, but also languages of the past and such additions as may be required in the future. The UCS uses a 4-octet (1 octet is 8 bits) structure to represent a character. However, the most significant bit of the most significant octet is constrained to be 0, which permits its use for private internal purposes in a data processing system. The remaining 31 bits allow us to represent more than two thousand million characters. The four octets are named as follows: • The Group-Octet, or G • The -Octet, or P • The Row-Octet, or R • The Cell-Octet, or C G is the most significant octet and C is the least significant octet. So, the whole code range for UCS is viewed as a four-dimensional structure composed of • 128 groups • 256 planes in each group • 256 rows in each plane • 256 cells in each row Two hexadecimal digits (0-9, A-F) specify the values of any octet. The values of G are restricted to the range 00-7F. The plane with G=00 and P=00 is known as the Basic Multilingual Plane (BMP). The row of BMP with R=00 represents the same set of characters as 8-bit ISO Latin-I. Therefore, the first 128 characters of ASCII, ISO Latin-1, and BMP with R=00 match. Characters 129th to 256th of ISO Latin-I and that of BMP with R=00 match. This makes UCS compatible with the existing 7-bit ASCII and 8-bit ISO Latin-I. Further, BMP has been divided into five zones. • A-zone: It is used for alphabetic and symbolic scripts together with various symbols. The code position available for A-zone ranges from 0000-4DFF. The code positions 0000-001F and 0080-009F are reserved for control characters. The code position 007F is reserved for the DELETE character. Thus, it has 19903 code positions available for graphics characters. • I-zone: It is used for Chinese/Japanese/Korean (CJK) unified ideographs. Its range is 4E00-9FFF, so 20992 code positions are available in this zone. • O-zone: It is used for Korean syllabic scripts and for other scripts. Its range is A000-D7FF, so 14336 code positions are available in this zone.

991 APPENDIX a ■ Character Encodings

• S-zone: It is reserved for use with transformation format UTF-16. The transformation format UTF-16 is described shortly. Its range is D800-DFFF, so 2048 code positions are available in this zone. • R-zone: It is known as the restricted zone. It can be used only in special circumstances. One of the uses of this zone is for specific user-defined characters. However, in this case an agreement is necessary between the sender and the recipient to communicate successfully. Its range is E000-FFFD, so 8190 code positions are available in this zone. UCS is closely related to another popular character set called Unicode, which has been prepared by the . Unicode uses a 2-octet (16 bits) coding structure and hence it can accommodate 216 (= 65536) distinct characters. The Unicode can be considered as the 16-bit coding of the BMP of UCS. These two character sets, Unicode and UCS, were developed and are maintained by two different organizations. However, they cooperate to keep Unicode and UCS compatible. If a computer system uses the Unicode character set to store some text, each character in the text has to be allocated 16 bits even if all characters in the text are from the ASCII character set. Note that the first 128 characters of Unicode match with that of ASCII, and a character in ASCII can be represented only in 8-bits. So, to use 16 bits to represent all characters in Unicode is wasteful of computer memory. An alternative would be to use 8 bits for all characters from ASCII and 16 bits for characters outside the range of ASCII. However, this method of using different bits to represent different characters from Unicode has to be consistent and uniform, resulting in ambiguity when data is stored or interchanged between different computer systems. This issue led to the development of the character encoding methods. Currently, there are four character-encoding methods specified in ISO/IEC 10646-1. • UCS-2 • UCS-4 • UTF-16 • UTF-8

UCS-2 This is a 2-octet BMP form of encoding, which allows the use of two octets to represent a character from the BMP. This is a fixed-length encoding method. That is, each character from BMP is represented by exactly two octets.

UCS-4 This encoding method is also called the 4-octet canonical form of encoding, which uses four octets for every character in UCS. This is also a fixed-length encoding method.

UTF-16 (UCS Transformation Format 16) Once characters outside the BMP are used, the UCS-2 encoding method cannot be applied to represent them. In this case, the encoding must switch over to use UCS-4, which will just double the use of resources, such as memory, network bandwidth, etc. The transformation format UTF-16 has been designed to avoid such a waste of memory and other resources, which would have resulted in using the UCS-4 encoding method. The UTF-16 is a variable-length encoding method. In the UTF-16 encoding method, UCS-2 is used for all characters within BMP and UCS-4 is used for encoding the characters outside BMP.

992 APPENDIX a ■ Character Encodings

UTF-8 (UCS Transformation Format 8) This is a variable-length encoding method, which may use 1 to 6 octets to represent a character from UCS. All ASCII characters are encoded using one octet. In the UTF-8 format of character encoding, characters are represented using one or more octets, as shown in Table A-2.

Table A-2. List of Legal UTF-8 Number of Octets Bit Patterns Used UCS Code

1 Octet 1: 0xxxxxxx 00000000-0000007F 2 Octet 1: 110xxxxx 00000080-000007FF Octet 2: 10xxxxxx 3 Octet 1: 1110xxxx 00000800-0000FFFF Octet 2: 10xxxxxx Octet 3: 10xxxxxx 4 Octet 1: 11110xxx 00010000-001FFFFF Octet 2: 10xxxxxx Octet 3: 10xxxxxx Octet 4: 10xxxxxx 5 Octet 1: 111110xx 00200000-03FFFFFF Octet 2: 10xxxxxx Octet 3: 10xxxxxx Octet 4: 10xxxxxx Octet 5: 10xxxxxx 6 Octet 1: 1111110x 04000000-7FFFFFFF Octet 2: 10xxxxxx Octet 3: 10xxxxxx Octet 4: 10xxxxxx Octet 5: 10xxxxxx Octet 6: 10xxxxxx

The “x” in the table indicates either a 0 or a 1. Note that, in UTF-8 format, an octet that starts with a 0 bit indicates that it is representing an ASCII character. An octet starting with 110-bit combinations indicates that it is the first octet of the 2-octet representation of a character, and so on. Also note that, when an octet is part of a multi-octet character representation, the octet other than the first one starts with a 10-bit pattern. Security checks can be easily implemented for UTF-8 encoded data. UTF-8 octet sequences, which do not conform to the octet sequences shown in the table, are considered invalid.

993 APPENDIX a ■ Character Encodings Java and Character Encodings Java stores and manipulates all characters and strings as Unicode characters. In serialization and byte codes, Java uses the UTF-8 encoding of the Unicode character set. All implementations of Java virtual machine are required to support the character encoding methods, as shown in Table A-3.

Table A-3. List of the Supported Character Encodings by a JVM Character Encoding Description

ASCII 7-bit ASCII (also known as ISO646-US, the basic Latin block of the Unicode character set). ISO-8859-1 ISO No. 1 (also known as ISO-LATIN-1). UTF-8 8-bit Unicode Transformation Format. UTF-16BE 16-bit Unicode Transformation Format, big-endian byte order. Big-endian is discussed in Chapter 3. UTF-16LE 16-bit Unicode Transformation Format, little-endian byte order. Little-endian is discussed in Chapter 3. UTF-16 16-bit Unicode Transformation Format, byte-order specified by a mandatory initial byte-order mark (either order accepted on input; big-endian used on output).

Java supports UTF-8 format with the following two significant modifications: • Java uses 16 bits to represent a NUL character in a class file, whereas standard UTF-8 uses only 8 bits. This compromise has been made to make it easier for other languages to parse a Java class file where a NUL character is not allowed within a string. However, in some cases, Java uses standard UTF-8 format to represent the NUL character. • Java recognizes only 1-octet, 2-octet, and 3-octet UTF-8 formats, whereas standard UTF-8 format may use 1-octet, 2-octet, 3-octet, 4-octet, 5-octet, and 6-octet sequences. This is because Java supports the Unicode character set and all characters from Unicode can be represented in 1-, 2- or 3-octet formats of UTF-8. When you compile the Java source code, by default, the Java compiler assumes that the source code file has been written using the platform’s default encoding (also known as local code page or native encoding). The platform’s default character encoding is Latin-1 on Windows and Solaris, and MacRoman on Mac. Note that Windows does not use true Latin-1 character encoding. It uses a variation of Latin-1 that includes fewer control characters and more printing characters. You can specify a file-encoding name (or code page name) to control how the compiler interprets characters beyond the ASCII character set. At the time of compiling your Java source code, you can pass the character-encoding name used in your source code file to Java compiler. The following command tells the Java compiler (javac) that the Java source code Test.java has been written using a traditional Chinese encoding named . Now, the Java compiler will convert all characters encoded in Big5 to Unicode. javac -encoding Big5 Test.java

994 APPENDIX a ■ Character Encodings

The JDK includes the native2ascii tool, which can be used to convert files that contain other character encoding into files containing Latin-1 and/or Unicode-encoded characters. The general syntax of using native2ascii tool is native2ascii option inputfile outputfile

For example, the following command converts all characters in Source.java file into Unicode-encoded characters and places the output in the Destination.java file assuming that the Source.java file has been written using the platform’s default encoding: native2ascii Source.java Destination.java

The following command converts all characters in the Source.java file into Unicode-encoded characters and places the output in the Destination.java file. It is assumed that the Source.java file has been written using Chinese Big5 encoding. native2ascii -encoding Big5 Source.java Destination.java

The following command performs the reverse operation, that is, it converts the Source.java file with Latin-1 and/or Unicode-encoded characters to the Destination.java file with native-encoded characters: native2ascii -reverse Source.java Destination.java

The native2ascii tool uses the standard output for the output if the outputfile name is omitted. It uses standard input for the input if the inputfile name is omitted too.

995 APPENDIX B

Documentation Comments

The Java lets you include comments in the source code that can be used to prepare documentation for the application. Such comments are known as documentation comments or Javadoc comments. JDK provides a javadoc command-line tool to extract the documentation comments from the source codes and generate documentation in HTML format. The javadoc tool is located in the bin directory of the JDK_HOME directory. For example, if you have installed the JDK in C:\java9 directory, the javadoc tool will be located in the C:\java9\bin directory. Execute the javadoc tool with --help and --help-extra to see all available options. Although a documentation comment can appear anywhere in Java source code, the javadoc tool uses only those documentation comments to generate the HTML pages that appear just before the declaration of classes, nested classes, interfaces, enums, annotations, constructors, methods, and fields. Note that the tool does not generate documentation for the documentation comments that are written for anonymous classes, package declarations, and import declarations. You need to write the documentation comments in a separate special file for a package, which will be used by the tool to generate documentation for that package.

■■Tip Java 9 introduced a new construct called a module. The javadoc tool supports documentation comments in module declarations.

A documentation comment starts with the /** characters and ends with the */ characters. The (*) on each line of the documentation comment are ignored. The following is an example of a documentation comment that is written for the Calc class declaration:

// Calc.java package com.jdojo.utility;

/** * A utility class to perform basic calculations on numbers. All * methods in this class are static. It provides methods * to perform addition, subtraction, multiplication, and division. * * @author Kishori Sharan */ public final class Calc { // Code for Calc class goes here }

© Kishori Sharan 2017 997 K. Sharan, Beginning Java 9 Fundamentals, https://doi.org/10.1007/978-1-4842-2902-6 APPENDIX B ■ Documentation Comments

It is important to note that the documentation comment must appear just before the declaration of the program element for which it is intended. Otherwise, it will be ignored by the javadoc tool or shown for the wrong element. The following two documentation comments are not the same:

/* Example #1 */ /** * This documentation comment is intended for the class declaration Xyz. However, it will be * ignored by the javadoc tool, because there is a package declaration between this * documentation comment and the Xyz class declaration. Note that a documentation comment for a * package declaration is written differently and it is not written in the source code. */ package com.jdojo.utility; public class Xyz { /* Code for Xyz class goes here */ }

/* Example #2 */ package com.jdojo.utility;

/** * This documentation comment is intended for the class declaration Xyz. It will be used by the * javadoc tool, because it appears just before the Xyz class declaration. */ public class Xyz { /* Code for Xyz class goes here */ }

Writing Documentation Comments You can write three types of comments in Java source code: • Single-line comments • Multi-line comments • Documentation comments The first two types of comments are free-form comments and they are meant for the developers to read. The third type of the comment is meant to be processed by the javadoc tool to generate HTML documents for the source code. The textual part of the documentation comment may include HTML tags, and those tags will be interpreted as HTML in the generated HTML document. For example, to display the text "Hello" in boldface as part of the documentation comment, you can write Hello as shown:

/** * You can include HTML tags in documentation comments. This will display Hello in * boldface font. */

998 APPENDIX B ■ Documentation Comments

■■Tip In Java SE 9, the javadoc tool supports HTML5 in documentation comments.

Apart from HTML tags, you can also use some special tags. A tag in a documentation comment is a special type of keyword that is interpreted and processed by the javadoc tool. Two types of tags can be used: • Block tags • Inline tags A block tag is of the following form:

@tagName tagText

A block tag starts with an @ character, which is followed by the tag name. The tag text follows the tag name. The following is an example of a block tag, which uses the @author block tag and Kishori Sharan as the tag text:

@author Kishori Sharan

A block tag must appear at the beginning of a line in a documentation comment. Note that the asterisks, whitespace, and the /** characters are ignored by the javadoc tool if they appear at the beginning of a line. When I state that a block tag must appear at the beginning of a line, I mean the beginning of a line after ignoring these characters. The following is an example of using the @author and @since block tags. The @author tag lets you specify an author name and the @since tag allows you to specify the version since the API was introduced.

/** * A utility class to perform basic calculations on numbers. All methods in this class are * static. It provides methods to perform addition, subtraction, multiplication, * and division. * * @author Kishori Sharan * @since Version 1.0 */ public final class Calc { // More code goes here }

If a line in a documentation comment starts with an @ character, it will be interpreted as the start of a block tag. If you want to start a line with an @ character without getting it interpreted as the start of a block tag, you need to use the HTML entity @ instead of the @ character. However, an @ character may appear as part of the text inside a line, provided the prior character isn’t a {, which is explained more next. The associated text with a block tag may appear in multiple lines, which includes all text that follows the tag name until another block tag or the end of the documentation comment is encountered. An inline tag can appear anywhere in the documentation comment where text can appear. It is of the form:

{@tagName tagText}

999 APPENDIX B ■ Documentation Comments

An inline tag is enclosed inside braces ({ and }). The following is an example of a documentation comment that uses a {@code text} inline tag to display the text n1 + n2 in code font:

/** * An example of inline tag. It computes {@code n1 + n2}. */

■■Tip When you are writing a documentation comment, make sure that the first sentence of the description selection of the comment is a summary sentence. The comment for a package, a class, and a member is split into two sections: a summary section and a detail section. The first sentence of the comment is displayed in the summary section and the entire comment is displayed in the detail section in the documentation.

List of Block and Inline Tags Not all tags can be used for the documentation comment in all contexts. Table B-1 contains the list contexts and the tags that can be used in those contexts. JDK 9 has added several tags to support documentation comments on a module's declaration and to enhance the generated Javadoc. I discuss them in in subsequent sections.

Table B-1. List of Block and Inline Tags, and the Contexts in Which They Can Be Used Context Available Tags

Overview @author, @see, @since, @serialField, @version, {@code}, {@docRoot}, {@index}, {@link}, {@linkplain}, {@literal} Module Declaration @author, @deprecated, @provides, @see, @since, @serialField, @uses, @version, {@code}, {@docRoot}, {@index}, {@link}, {@linkplain}, {@literal} Package Declaration @author, @see, @since, @serialField, @version, {@code}, {@docRoot}, {@index}, {@link}, {@linkplain}, {@literal} Type Declaration @author, @deprecated, @hidden, @param, @see, @since, @serialField, @version, {@code}, {@docRoot}, {@index}, {@link}, {@linkplain}, {@literal} Constructor and Method @deprecated, @exception, @hidden, @param, @return, @see, @since, Declaration @serialData, @throws, @version, {@code}, {@docRoot}, {@index}, {@inheritDoc}, {@link}, {@linkplain}, {@literal} Field Declaration @deprecated, @hidden, @see, @since, @serial, @serialField, {@code}, {@docRoot}, {@index}, {@link}, {@linkplain}, {@literal}, {@value}

The Overview context in the table may not be obvious, because there is no such construct as “overview” in the Java programming language. The javadoc tool lets you add documentation comments for the entire application in one place, which is called an overview comment. The overview comment is displayed on the overview page that is generated by the tool. I discuss an example of how to include an overview comment in the generated documentation later. The following sections describe the tags in brief.

1000 APPENDIX B ■ Documentation Comments

@author The @author tag adds the author name or names under the Author section in the documentation. A documentation comment may contain multiple @author tags. If you have multiple author names, you can use only one @author tag to specify all author names or you can use a separate @author tag to specify each author name. If you use multiple @author tags, all author names will be concatenated using a locale-specific separator and placed under one Author entry. Table B-2 shows the effects of using one and multiple @author tags. Note that the table shows only the Author entry from the generated text.

Table B-2. The Effects of Using One and Multiple @author Tags in Documentation Comments Documentation Comment Generated Author Entry

/** Author: * A dummy class. Kishori Sharan * * @author Kishori Sharan */ /** Author: * A dummy class. Kishori Sharan, Greg Langham, John Jacobs * * @author Kishori Sharan * @author Greg Langham * @author John Jacobs */

@deprecated The @deprecated tag is used to generate documentation for program elements that should no longer be used, although they may function correctly. The explanation text for this tag should explain why the program element should not be used. If there is a replacement for the deprecated program element, the explanation text should contain a link to or explanation about the replacement. The following documentation comment uses the @deprecated tag for the Dummy class. It provides a link to Dummy2 class, which is the replacement class.

/** * A dummy class. * * @deprecated As of version 1.1. Use {@link com.jdojo.utility.Dummy2 Dummy2} instead. */ public class Dummy { }

@exception The @exception tag is a synonym for the @throws tag. Refer to the description of the @throws tag for details.

1001 APPENDIX B ■ Documentation Comments

@param The @param is applicable only to classes, methods, and constructors. It generates a Parameters section with the specified parameter-name and the description. If the parameter is a type parameter, the specified parameter-name should be enclosed in angle brackets (<>). The following is an example of using the @param tags to document the parameters of a method:

/** * Returns the result of multiplication of n1 and * n2. It may return incorrect result if the value of * the multiplication of n1 and n2 exceeds * the range of the int . * * @param n1 The multiplicand * @param n2 The multiplier * @return Returns the result of multiplication of n1 and n2 */ public static int multiply(int n1, int n2) { return n1 * n2; }

The following is an example of using the @param tags to document the type parameters of a class:

/** * Wraps an object of any type. * * @param Type of the object wrapped in the Wrapper */ public class Wrapper { // Code for the Wrapper class goes here }

@return It is valid only for methods. It adds a Returns section with the specified description. The specified description should contain the return type and the description of value that is returned from the method. Refer to the example of the @param tag to see how to use @return tag in a documentation comment.

@see It adds a See Also section with a link or text that points to the specified reference. A documentation comment can have multiple @see tags. All @see tags will be displayed under one See Also section for a documentation comment. You can specify the reference in one of the three following forms:

@see "text" @see label @see package.Classname#member label

In the first form, the reference is specified as text that is enclosed in double quotes. The javadoc tool adds the specified text in the See Also section, without any link.

1002 APPENDIX B ■ Documentation Comments

In the second form, the reference is specified using an HTML anchor tag ( tag). The javadoc tool generates a hyperlink that points to the specified URL. If specified, the specified label is displayed as the link text. In the third form, the reference is specified to a class, an , a field, a constructor, or a method. Note that if you are referencing a field, a constructor, or a method, its name is preceded by a hash sign (#), not a dot. The javadoc tool generates a link to the reference that has the specified label as the visible text. The label is optional. If label is omitted, the tool uses a suitable text for the link that is derived from the first argument to the @see tag. The reference to the program element could use the fully qualified name or a partial name. The tool uses the same rules as the Java compiler to resolve the partial name of a program element. The following is an example of how to use different forms of the @see tag. It assumes that Calc class is in the same package as the Dummy class and the Calc class contains the add() and multiply() methods. package com.jdojo.utility;

/** * A dummy class. * * @see "Online Java Tutorial" * @see Oracle Website * @see com.jdojo.utility.Calc Calculator * @see com.jdojo.utility.Calc#add(int, int) Add Method * @see com.jdojo.utility.Calc#multiply(int, int) */ public class Dummy { }

The generated See Also section for the Dummy class would look as shown:

See Also: "Online Java Tutorial" Oracle Website, Calculator, Add Method, Calc.multiply(int, int)

@serial The javadoc tool generates a Serialized Form page that contains all pieces of information about serialized forms of all serialized classes. The tool creates a See Also section for serialized classes that contains a link to the Serialized Form page. A class needs to implement java.io.Serializable or java.io.Externalizable interface to be added to the Serialized Form page. The @serial tag is used to add a description for default serializable fields of a class. The specified description will be added to the Serialized Form page for the field. The following is an example of using the @serial tag for a field:

/** * A dummy class. */ public class Dummy implements java.io.Serializable { /** * @serial The description for value field goes here */ private int value; }

1003 APPENDIX B ■ Documentation Comments

You may include or exclude a package or a class from appearing on the Serialized Form page by using the include or exclude argument with the @serial tag. If the @serial tag is used at both package and class levels, the class-level tag takes precedence. By default, a serializable class that is public or protected is included in the Serialized Form page. The following documentation comment excludes the Dummy class from the Serialized Form page:

/** * A dummy class. It will not appear on the serialized Form page. * * @serial exclude */ public class Dummy implements java.io.Serializable { /** * @serial The description for value field goes here */ private int value; }

@serialData A class that implement java.io.Externalizable interface needs to implement the readExternal() and writeExternal() methods. A serializable class may also implement the writeObject(), readObject(), writeReplace(), and readResolve() methods to customize the serialization of the objects of the class. The @serialData tag may be used with the documentation comments of any of these six methods. The data description text should describe the types and the order of the data in the serialized form.

@serialField A serializable class can include a serialPersistentFields field that is an array of ObjectStreamField. The @serialField tag describes each component of that array. The description of the elements will appear in the Serialized Form page. The following documentation comment uses @serialField tags to document the name and the height components of the ObjectStreamField: package com.jdojo.utility; import java.io.ObjectStreamField; import java.io.Serializable;

/** * A class to represent a person */ public class Person implements Serializable { private String name; private String gender; private double height;

1004 APPENDIX B ■ Documentation Comments

/** * @serialField name String The name of the person * @serialField height double The height of the person in feet */ private static final ObjectStreamField[] serialPersistentFields = {new ObjectStreamField("name", String.class), new ObjectStreamField("height", double.class) }; }

@since The @since tag adds a Since section to the documentation. The specified description indicates the release of the software that added the program element being documented. The following documentation comment shows how to use the @since tag:

/** * A dummy class. * * @since 1.0 */ public class Dummy { }

@throws The @throws tag is a synonym for the @exception tag. It adds a Throws section to the documentation. It is used to describe an exception that may be thrown from a constructor or a method. Multiple @throws tags can be used in a documentation comment. If a method throws a checked exception and there is no @throws tag, the javadoc tool will add one without a description to make sure that all checked exceptions are documented. The following documentation comment for the divide() method shows how to use the @throws tag. If you do not provide the fully qualified name of the class, the javadoc tool will use the same search order as used by the Java compiler to resolve the partial class name.

/** * Returns the result of integer division of n1 by * n2. * * @param n1 The dividend * @param n2 The divisor * @return Returns the result of n1 / n2 * @throws ArithmeticException If n2 is zero. */ public static int divide(int n1, int n2) throws ArithmeticException { return n1 / n2; }

1005 APPENDIX B ■ Documentation Comments

@version The @version tag adds a Version section to the generated documentation. The version text should contain the current version of the program element. The @since tag is used to specify the version of the software when a program element was added, whereas the @version tag is used to specify the current version. The following documentation comment shows how to use the @version tag:

/** * A dummy class. * * @since 1.0 * @version 1.6 */ public class Dummy { }

{@code } It displays the specified text in code font without interpreting the text as HTML markup or nested documentation comments tag. It is equivalent to the following:

{@literal }

{@docRoot} It resolves to the relative path of the root directory of the generated documents. It is used in the URL part of links. Suppose you have a file called myfiles/copyright. that is located under the root directory of the generated documents. If you want to include a link to the copyright.html file in your documentation comment, you can do the following:

/** * A dummy class. Please read * the Copyright page. */ public class Dummy { }

{@inheritDoc} It copies the documentation of a method from the nearest inheritable class or the implementable interface. Note that for this tag to copy the documentation, the method in which this tag appears must override a method in its parent class or implement a method of the implemented interfaces. This tag may be used only inside the main description in the documentation comment for a method or inside the text argument of @return, @param, and @throws tags for a method. If it appears inside the main description, it copies the main description of the overridden method. If it appears in other tag's text, it copies the tag's text from the overridden method. If a method overrides a method in the parent class or implements a method of an interface, the javadoc tool automatically copies the documentation for the main description, @return, @param, and @throws if the main description of these tags is missing in the overriding method.

1006 APPENDIX B ■ Documentation Comments

The following documentation comment demonstrates the use of the {@ inheritDoc} tag. It is used inside the documentation comment for the getId() method of the SmartPerson class. It is used inside the main description as well as the text section of the @return tag. Note that the @param tag is missing from the getId() method of the SmartPerson class. The javadoc tool will automatically copy the documentation for the @param tag from the getId() method of the Person class.

/** * A class to represent a person */ public class Person { /** * Returns the person id. * @param x The value to add to the id * @return The person id. */ public int getId(int x) { return x + 10; } }

/** * A class to represent a smart person */ public class SmartPerson extends Person { /** * {@inheritDoc} * @return {@inheritDoc} */ public int getId(int x) { return 20 + x; } }

The generated documentation for the getId() method of the SmartPerson class is as follows: getId public int getId(int x) Returns the person id.

Overrides: getId in class Person

Parameters: x - The value to add to the id

Returns: The person id.

1007 APPENDIX B ■ Documentation Comments

{@link

/** * A dummy class. Please see * {@link com.jdojo.utility.Calc#add(int, int) add} method of the * Calc class to learn how to add two integers. * */ public class Dummy { }

{@linkplain

{@literal } It displays the specified text without interpreting it as HTML markup or a nested documentation comment tag. Note that HTML tags are enclosed in angle brackets (<>). If you want to use angle brackets in documentation comments, you need to use the HTML entities < and >. If you do not want to use HTML entities, you can use this tag with your raw text. For example, it is valid to write {@literal x < y} anywhere in the documentation comment rather than writing x < y.

{@value } It is used to copy the value of a static and final field (a constant field). If it is used without the argument, it copies the value of the constant field at its location. The following documentation comments show how to use {@value} tag. In the documentation comment for the MULTIPLIER field, it uses the {@value} tag without an argument, which will insert the value of the MULTIPLIER field. In the documentation comment for the DIVISOR field, it uses both forms of the {@value} tag, one with an argument and one without an argument. The argument, #MULTIPLIER, refers to the MULTIPLIER field of the same class.

/** * A dummy class. */ public class Dummy { /** * The MULTIPLIER is {@value} */ public static final int MULTIPLIER = 2000;

1008 APPENDIX B ■ Documentation Comments

/** * The value of MULTIPLIER is {@value #MULTIPLIER}. * The value of DIVISOR is {@value}. */ public final static int DIVISOR = 1000; }

The following is the generated documentation comment that shows the effects of using the {@value} tag:

MULTIPLIER public static final int MULTIPLIER

The MULTIPLIER is 2000

DIVISOR public static final int DIVISOR

The value of MULTIPLIER is 2000. The value of DIVISOR is 1000.

@hidden JDK 9 introduced the @hidden block tag. It hides a program element from the generated API documentation. There are ways to hide program elements from the generated Javadoc; for example, all private members of a type are not part of the Javadoc unless you specify the option with the javadoc tool to include them. Use the @hidden tag to hide program elements, which is otherwise not possible to be excluded using any other options. Typically, I create a Test class in each module to test my logic when I work on a chapter. I can hide the Test class from appearing in the Javadoc using the @hidden tag as shown:

// Test.java package com.jdojo.utility;

/** * @hidden */ public class Test { public static void main(String[] args) { // Code goes here } }

{@index } JDK 9 introduced the @index inline tag. It can be used to tell the javadoc tool to index a keyword. It can appear in Javadoc as follows:

{@index }

1009 APPENDIX B ■ Documentation Comments

Here, is the keyword to be indexed and is the keyword’s description. If the keyword is a phrase consisting of multiple words, enclose it in double quotes. The following Javadoc tag is an example of using the @index tag with a keyword, jdojo:

{@index jdojo Info site (www.jdojo.com) for the Java 9 Revealed book!}.

@provides JDK 9 introduced the @provides block tag. You can use it only in a module's declaration. It documents an implementation of a service provided by the module. The description may specify how to obtain an instance of this service provider and other details of the provider. The following declaration of a module shows an example.

/** * @provides com.jdojo..PrimeChecker Provides a generic implementation for the PrimeChecker * service. */ module jdojo.prime.generic { requires com.jdojo.prime;

provides com.jdojo.prime.PrimeChecker with com.jdojo.generic.GenericPrimeChecker; }

@uses JDK 9 introduced the @uses block tag. You can use it only in a module's declaration. It documents that a service may be used by this module. The description may specify the details of the provider. The following declaration of a module shows an example.

/** * @uses com.jdojo.prime.PrimeChecker Loads the PrimeChecker services */ module jdojo.prime { exports com.jdojo.prime;

uses com.jdojo.prime.PrimeChecker; }

Documenting Packages A package declaration appears multiple times in an application. There needs to be a simpler and separate way to document a package. You can document a package by placing either of the following two files, but not both, in the package directory along with the source files (.java files): • package-info.java • package.html

1010 APPENDIX B ■ Documentation Comments

■■Tip If both package-info.java and package.html files are available, the package-info.java file is used.

When you run the javadoc tool, it automatically uses the documentation in one of these two files as the documentation for your package. The first sentence of the package documentation should be a summary statement about the package. The first sentence of the package documentation is displayed in the package summary description. com/jdojo/utility/package-info.java file It contains the package declaration with documentation comments for a package. In a package-info.java file, a package is documented the same way as any other program elements are documented. The content of the package-info.java file for the com.jdojo.utility package is as follows:

/** * Contains utility classes. More description for * com.jdojo.utility package goes here. * @since 1.1 * @version 2.0 */ package com.jdojo.utility; com/jdojo/utility/package.html file It is a regular HTML file with HTML tags. The HTML contents within the and tags are used as the package documentation. It does not contain a package declaration. It does not use the /** and */ characters as the start and end of the documentation comment. However, you can use documentation tags that are valid for the package. The content of the package.html file for com.jdojo.utility package is as shown:

Contains utility classes. More description for com.jdojo.utility package goes here. @since 1.1 @version 2.0

1011 APPENDIX B ■ Documentation Comments Overview Documentation The overview documentation is used to write documentation for the entire application in a separate HTML file. There is no rule for naming the overview documentation file. Generally, it is named as overview.html. The comment is placed inside the and tags in the HTML file. You need to pass the path of this file to the javadoc tool using the –overview command-line option. The following is a sample overview comment contained in an HTML file:

API documentation for the dummy application. More overview text goes here. @author Kishori Sharan @version 2.0

Including Unprocessed Files in Documentation Sometimes you may want to include some files with your Java documentation, which you reference inside the documentation comments. For example, you may want to display graphics or source code. The javadoc tool lets you include files, which it copies to the generated documentation directory without processing them. You need to create a directory called doc-files under any package directory that contains .java source files and copy your extra files in that directory. The javadoc tool will copy all your files to the destination directory without processing them.

Skipping Source Files Processing Sometimes you may have some Java source files that you do not want the javadoc tool to process. For example, you may have some test files for which you do not want to generate documentation. The javadoc tool looks at the file name before it decides to process the content of the file. If the file name is not a valid Java identifier, it skips that file. If you have a .java source file, which the javadoc tool should skip, you need to name that file such that the name is not a valid Java identifier. For example, you may include a hyphen (-) in the file name to skip it. Note that this strategy of skipping source file processing is needed when you are using the javadoc tool to generate documentation by passing it wildcards (*) or package name. If you supply the javadoc tool the list of source files to process, you do not need to use this strategy.

An Example of Documentation Comments Listing B-1 contains the declaration of com.jdojo module with documentation comments. Listing B-2 contains the source code for a Calc class. It is a trivial class. Its purpose is only to demonstrate how to write documentation comments. It uses many of the tags I discussed earlier. Note the use of the @index tag in the documentation comment for the Calc class, which will make the term jdojo searchable in the generated Javadoc. The term jdojo is also searchable because it is part of many modules and packages.

1012 APPENDIX B ■ Documentation Comments

Listing B-1. The Declaration of a jdojo.utility Module // module-info.java /** * A utility module that shows you how to use documentation comments. * * @author Kishori SHaran * @since 2.0 */ module jdojo.utility { exports com.jdojo.utility; }

Listing B-2. Calc Class Source Code with Documentation Comment // Calc.java package com.jdojo.utility;

/** * A utility class to perform basic calculations on numbers. * All methods in this class are static. It * provides methods to perform addition, subtraction, * multiplication and division. * * {@index jdojo Visit www.jdojo.com for more info on Beginning Java 9 Fundamentals book!} * * @author Kishori Sharan * @since Version 1.0 */ public final class Calc { /** * Stop someone from instantiating this class. This class is not * meant for instantiation as all its methods are * static. */ private Calc() { }

/** * Performs addition on two numbers. It returns the result of * n1 + n2 as an int. If the result * of n1 + n2 exceeds the range of the * int data type, it will not return the correct * result. For bigger numbers, use {@link #add(long, long)}. * * @param n1 The first number * @param n2 The second number * @return Returns the value of n1 + n2 */

1013 APPENDIX B ■ Documentation Comments

public static int add(int n1, int n2) { return n1 + n2; }

/** * Performs addition on two numbers. It returns the result of * n1 + n2 as a long. * * @param n1 The first number * @param n2 The second number * @return Returns the value of n1 + n2 */ public static long add(long n1, long n2) { return n1 + n2; }

/** * Returns the result of n1 - n2. * * @param n1 The first number * @param n2 The second number * @return Returns the result of n1 - n2 */ public static int subtract(int n1, int n2) { return n1 - n2; }

/** * Returns the result of multiplication of n1 and * n2. It may return incorrect result if the value of * the multiplication of n1 and n2 * exceeds the range of the int data type. * * @param n1 The multiplicand * @param n2 The multiplier * @return Returns the result of multiplication of * n1 and n2 */ public static int multiply(int n1, int n2) { return n1 * n2; }

/** * Returns the result of integer division of n1 by * n2. * * @param n1 The dividend * @param n2 The divisor * @return Returns the result of n1 / n2 * @throws ArithmeticException If n2 is zero. */

1014 APPENDIX B ■ Documentation Comments

public static int divide(int n1, int n2) throws ArithmeticException { return n1 / n2; } }

Running the javadoc Tool You need to run the javadoc command-line tool to generate HTML pages for your documentation comments in the source files (.java files). In JDK 9, the javadoc tool has been enhanced to work with modules. It is easier to generate the Javadoc for multiple modules, if you place the source code for all your modules into one directory, which contains a subdirectory named after each module. In the source code supplied with this book, I created a directory Java9Fundamentals/docsrc, which contains the source code for the jdojo.utility and jdojo.jshell modules. The contents of the docsrc subdirectory is as follows. For these examples of running the javadoc tool, I assume that the following files contain documentation comments: • Java9Fundamentals/docsrc/jdojo.jshell/com/jdojo/jshell/JShellApiTest. java • Java9Fundamentals/docsrc/jdojo.jshell/com/jdojo/jshell/Person.java • Java9Fundamentals/docsrc/jdojo.jshell/module-info.java • Java9Fundamentals/docsrc/jdojo.utility/com/jdojo/utility/Calc.java • Java9Fundamentals/docsrc/jdojo.utility/com/jdojo/utility/package-info. java • Java9Fundamentals/docsrc/jdojo.utility/module-info.java • Java9Fundamentals/docsrc/overview.html The overview.html file is the overview documentation file for the documentation. There is a package- info.java file for the com.jdojo.utility package. Calc.java is a Java source file. The module-info.java file contains the module declaration for the jdojo.utility module. If you copied the source code for this book in C:\Java9Fundamentals, the C:\Java9Fundamentals\docsrc directory contains the .java source files for the two modules. The syntax to run the javadoc tool is as follows: javadoc [options] [@args-file-paths]

[options] is zero or more command-line options for the javadoc tool. Options are used to customize the output. For example, the –d option lets you specify the output directory where the javadoc tool will store all generated output files and the --module option lets you specify the names of the modules whose documentation you want to generate. The <@args-file-paths> lets you include arguments for the tool in files. Sometimes the comment text for the javadoc tool becomes too big. Some command prompts have limitations on how many characters can be entered as part of a command. In those circumstances, you can place the command-line arguments in one or more arguments files and supply those argument file paths as the arguments to the javadoc tool. Note that the arguments file path is preceded by the @ sign. The javadoc tool does not support –J options and wildcards (*) in an argument file.

1015 APPENDIX B ■ Documentation Comments

■■Tip The javadoc tool provides many options to customize the generated output files. To list all options, you can run it using the --help option. You can use a –J-version option to print the version of the javadoc tool.

The following command will generate Javadoc for you:

C:\Java9Fundamentals>javadoc -d docs -html5 -author -version --module-source-path docsrc --module jdojo.utility,jdojo.jshell -overview docsrc\overview.html

Here are the details of each part in the command: • The current directory is C:\Java9Fundamentals. • The -d docs option specifies that the generated Javadoc should be copied to the C:\Java9Fundamentals\docs directory. • The -html5 option specifies that the generated output should be in HTML 5. This option was added in Java 9. • By default, the javadoc tool does not generate documentation for the @author and @version tags. The –author and -version options instruct the tool to include the text for the @author and @version tags in the generated documentation, respectively. • The --module-source-path docsrc option specifies that the source for modules is in the C:\Java9Fundamentals\docsrc directory. • The --module jdojo.utility,jdojo.jshell option indicates that you want to generate Javadoc for the two modules—jdojo.utility and jdojo.jshell. If you want to generate Javadoc for more modules, place their source code in the docsrc directory and include their names in this list. • The -overview docsrc\overview.html option specifies the location of the HTML file that contains the overview comment for the application for which you are generating the Javadoc. You can use one or more argument files to store all the arguments to the javadoc tool. Note that –J options and wildcards (*) are not supported in argument files. You must use the command line to enter these two types of arguments. Suppose the following is the contents of a file named args.txt, which is placed in the C:\Java9Fundamentals directory:

-d docs -html5 -author -version --module-source-path docsrc --module jdojo.utility,jdojo.jshell -overview docsrc\overview.html

You can run the javadoc tool that will use arguments from the args.txt file, as shown here. All relative paths in the argument file are resolved with respect to the current directory.

C:\Java9Fundamentals>javadoc @args.txt

1016 APPENDIX B ■ Documentation Comments

You can split the arguments for the javadoc into multiple files. You can pass multiple argument files to the javadoc tool by separating them by a space, as shown here. Options can be distributed among multiple argument files in any order. You can use a relative path (e.g., args.txt) or the absolute path (e.g., C:\ Java9Fundamentals\args.txt) of the argument file to the javadoc tool.

C:\projects>javadoc @args1.txt @args2.txt @args3.txt

The NetBeans IDE lets you generate Javadoc for your project. On the Properties dialog box for your project, choose Build --> Documenting to get the Javadoc properties sheet, where you can specify all options for the javadoc tool. To generate the Javadoc, select Generate Javadoc from the right-click menu options for your project or from the Run menu.

Generated Documentation Files The javadoc tool generates many HTML files. All generated files can be classified into three categories: • Files for modules, classes, interfaces, enums, annotations, packages, and overviews • Files to cross-reference some pieces of information from one HTML page to another, such as an index page, a class hierarchy page for each package, a use page for each package, etc. • Support files The tool generates one HTML file per class/interface/enum/annotation. The files are placed in directories that mimic the package hierarchies of classes, interfaces, enums, and annotations. The file names are the same as the program elements for which they contain the documentation. A package-summary.html file is included in every package directory that contains package documentation. An overview-summary. html file is generated for all packages to serve as overview documentation. Separate pages are generated for modules. The generated HTML pages include the class hierarchy pages, a deprecated API page, constants values pages, serialized forms pages, etc. These files have self-explanatory names and they contain a hyphen in their names. Support files include any image files, a help-doc.html file to describe the generated documentation files, etc.

Viewing Generated HTML Documentation You can view the documentation generated by the javadoc tool in an HTML page using HTML frames or with no frames. The javadoc tool generates an index.html file, which is placed at the root in the output directory. You need to open the index.html file in a browser, for example, , Google Chrome, Mozilla Firefox, Safari, etc., to view the documentation using HTML frames. You can click the FRAMES and NO FRAMES links at any time to switch between HTML frames and no frames view of the documentation. The HTML frames are organized as shown in Figure B-1.

1017 APPENDIX B ■ Documentation Comments

Navigation Bar

Modules/Packages

Details Navigation Bar

Classes

Figure B-1. Arrangement of the HTML frames that are generated by the javadoc tool

Figure B-2 shows the index.html page opened in Frames mode for the Javadoc that you created. It shows the Javadoc for the Calc class in the com.jdojo.utility package.

Figure B-2. The generated HTML page for the Calc class

In Frames mode, the index.html page contains three frames: • A Modules/Packages frame at top-left • A Classes frame at bottom-left • A Details frame at right The top-left frame contains the list of all classes, all packages, and all modules. The navigation bar contains links to switch between these views in the top-left frame. If the documentation that you generate contains only one package, this frame is not generated. That is, you must generate documentation for at least two packages in order for the javadoc tool to generate the Modules/Packages frame. In the upper-left

1018 APPENDIX B ■ Documentation Comments frame, you can view all packages or all modules. When you click on a module, the upper-left frame displays all packages in that module. The navigation bar in the bottom-left frame display a link with the selected module or package as the text. When you click this link, the Details frame displays the documentation for the module or the package. The bottom-left frame contains the list of classes, interfaces, enums, exceptions, and annotations in a package that is selected from the Module/Packages frame. The frame on the right side displays the details of the selection from the left frames.

Searching Javadoc Consider this scenario. You are looking for logic to implement something in Java and you find a piece of code on the Internet, which uses a class, but does not show the import statement importing that class. You have access to the Javadoc for Java SE and you want to know little more about the class. How do you get the package name of the class, which is needed to get to the documentation of the class? You search the Internet again. This time, search for the class name, which might get you a link to the Javadoc for the class. Alternatively, you can copy and paste the piece of code in a Java IDE such as NetBeans and Eclipse, and the IDE will help you generate the import statements to give you the package name of the class. Don’t worry about this inconvenience of searching for the package name of a class in Java 9. There is another addition to the Details frame in the Javadoc generated by the javadoc tool. All pages in this frame display a Search box on the top-right (see Figure B-2). The search box lets you search the Javadoc. The javadoc tool prepares an index of terms that can be searched. To know what is searchable, you need to know the terms that are indexed: • You can search for declared names of modules, packages, types, and members. The type of formal parameters of constructors and methods are indexed, but not the names of those parameters. So, you can search on the type of formal parameter. If you enter "(String, int, int)" in the search box, it will find you the list of constructors and methods that take three formal parameters of String, int, and int. If you enter "util" as a search term, it will show you a list of all packages, types, and members that contain the term "util" in their names. • You can search for all keywords and phrases specified with an @index inline tag. Everything else that is not listed in this list is not searchable using the Javadoc search box. The search box displays the found results as a list when you enter the search term. The results list is divided into categories such as Modules, Packages, Types, Members, and SearchTags. The SearchTags category contains results found from the indexed keywords that are specified using @index tags.

■■Tip The Javadoc search does not support regular expressions. The entered search keyword is searched for its occurrence anywhere in the indexed terms.

Figure B-3 shows using the Javadoc search box with the list of results. I generated the Javadoc for the com.jdojo.utility module and used it to search for jdojo, as shown on the left of the figure. I used the Javadoc for Java SE 9 to search for the term, Module, as shown on the right of the figure.

1019 APPENDIX B ■ Documentation Comments

Figure B-3. The Javadoc search box with keywords and searched results

You can use the Up and Down to navigate through the search results. You can view the details of the search results in one of the following two ways: • Click on a search result to open the Javadoc for that topic. • When a search result is highlighted using the Up/Down arrows, press Enter to open the details about that topic.

■■Tip You can use the -noindex option with the javadoc tool to disable the Javadoc search. No index will be generated and no search box will be available in the generated Javadoc.

A Javadoc search is performed locally using client-side JavaScript. There is no computation or search logic implemented in the server. If you have disabled JavaScript in your browser, you will not be able to use the Javadoc search feature.

Summary Java allows writing comments in source code that can be used to generate documentation. The documentation comment starts with /** and ends with */. The javadoc tool, which is included in the JDK, is used to extract and generate the documentation comments from source code. The tool generates documentation in HTML format. The tool contains support for many custom tags with special meaning. It also lets you use HTML tags inside the documentation. Apart from HTML tags, you can also use some special tags. A tag in a documentation comment is a special type of keywords that is interpreted and processed by the javadoc tool. Two types of tags can be used: block tags and inline tags.

1020 APPENDIX B ■ Documentation Comments

A block tag starts with an @ character, which is followed by the tag name. The tag text follows the tag name. A block tag must appear at the beginning of a line in a documentation comment. Note that the asterisks, whitespace, and the /** characters are ignored by the javadoc tool if they appear at the beginning of a line. An inline tag can appear anywhere in the documentation comment where text can appear. An inline tag is enclosed in braces. JDK 9 introduced the following new Javadoc tags: @hidden, @provides, @uses, and {@index}. The @hidden tag hides a program element in the generated Javadoc. The @provides and @uses tags are used only on module declarations to document the services provided and used by modules. The {@index} tag is used to specify a searchable keyword in the Javadoc. JDK 9 adds a Search box at the top-right of each page. You can search for program element names and the keywords specified with the {@index} tag. If you do not want the Search box to appear in the generated Javadoc, use the -noindex option with the javadoc tool. JDK 9 has also added several new options for the javadoc tool to work with modules.

1021 Index

„„ A Apparent polymorphism, 26 Apparent solar day, 553 Abstract data types (ADT), 21 Application programming interface (API), 94 Access level modifier, 235 applyPattern() method, 641 access levels for class members, 276 ArithmeticException class, 473 Account class, 282 Arithmetic operators, 150 behavior, 285–286 modulus operator (%), 157–159 modification, 284 addition (+), 151–153 balance instance variable, 283 compound arithmetic assignment class members, 277 operators, 160–161 compile-time errors, 279 increment and decrement, 161–164 credit() method, 284, 287 subtraction (–), 153–154 debit() method, 284, 286 unary minus operator, 159 different package, 280 unary plus operator, 159 getBalance() method, 284 Arity, 288 getV1() and setV1() methods, 279 arraycopy() method, 711, 714 inheritance, 335 ArrayList and Vector classes, 714 instance, 335 Array parameter isValidAmount() method, 287 clone() method, 720 package-level access, 275, 281, 286 clonedIds array, 721 private, 275, 286, 333–335 clonedNames array, 721 protected, 275, 333 elements, 723 public, 275, 277, 333–334 method declarations, 717–718 public instance variable, 281 object reference, 724–726 same package, 278 reference, 722–723 sample class, 276 swap() method, 718–719 singleton pattern, 335 toString() method, 718 static modifier, 277 Arrays Test class, 333 ArrayList/Vector, 742–743 T2.getInstance() method, 335 assignment compatibility, 740–741 Accumulator, 553 bounds checks, 737–738 Actual parameters, 258 class, 738–740 add() method, 257–260 command-line arguments, 726–730 Adder, 553 comparing, 746–748 addTen procedure, 7 conversion, 745–746 addUnsigned() method, 448 copying, 748 Ad hoc polymorphism, 26 declaration syntax, 736–737 Aggregation, 815 definition, 701 Aggregator module, 384, 392 elements, 704 Ahead-of-time (AOT), 3 explicit array initialization, 709–710 Ancestors, 759 filling, 748–749 Anonymous class, 338

© Kishori Sharan 2017 1023 K. Sharan, Beginning Java 9 Fundamentals, https://doi.org/10.1007/978-1-4842-2902-6 ■ INDEX

Arrays (cont.) sub class, 769 hash code, 749 super class, 769 initialization, 706–707 late binding jdojo.array module, 701 emp.setName() method, 772 length, 705–706 fields and methods, 773–775 limitations, 710–714 LateBindingSub class, 773–775 loop, 735–736 LateBindingSuper class, 773, 774 objects, 703–704 print() method, 773–775 parallel accumulation, 749 setName() method, 772 parameter, 717–722 myObject reference variable, 768 performing array operations, 743–745 Bitwise complement operator, 181 reference type, 708–709 Bitwise operators, 180–184 searching, 746 Block statement sorting, 750 if-else statement, 195–200 variable declarations, 701–702 switch, 200–203 variable-length arrays, 714–717 variable declaration, 194 Assertions Boolean class, 447 definition, 511 Boolean logical operators, 174–175 enabling/disabling, 515–516 compound Boolean logical assignment getPrice() method, 512 operators, 179 snippet of code, 518 logical AND operator (&), 177 statements, 511–513 logical NOT operator (!), 175–177 testing, 513–515 logical OR operator (|), 178 usage, 517–518 logical short-circuit OR operator (||), 178 Assignment operator, 147–149 Break statement, 212, 214–216 atXxx() methods, 562 Bug, 13 Autoboxing/unboxing, 449–451 Bytecode, 60 collections, 457–458 comparison operators, 455–457 overloaded method, 452–455 „„ C Calendar systems, solar, 556 Calling a method, 258 „„ B Car class Barycentric Dynamical Time (TDB), 553 changeString() method, 316 Basic Multilingual Plane (BMP), 991 Civic LX model, 311 Big-endian, 140–141 compiler error, 316 Binary floating-point system main() method, 314 advantages, 131 model, year, and price statements, 310 32-bit single-precision, 131–132 myCar = new Car() statement, 308, 309 denormalized floating-point numbers, 130 null reference, 308, 311 exponent, 132 rvalue, 309 IEEE single-precision, 132 swap() method, 312 IEEE 754-1985 standard, 131 test() method, 314 significand, 133 two Car objects, 310 Binary operator, 145 xyCar = myCar statement, 309 binarySearch() method, 746 CatTest class, 325 Binding changeString() method, 316 dynamic/runtime binding, 768 Character classes, 673 early binding Character encoding method EarlyBindingSub class, 771, 772 abstract character, 985 EarlyBindingSuper class, 771, 772 ASCII ebSub variable, 772 8-bit character set, 990–991 field access, 769 character set., 986–990 fields and methods, 770–771 NUL and DELETE, 986 print() method, 773 SPACE character, 986

1024 ■ INDEX

character repertoire, 985 fields, 224, 226, 252 coded character set, 985 Human jack, 227 code point, 985 import declarations, 236–238, 241–246 definition, 986 import-on-demand declaration, 239–241 glyph, 985 initializing, 224 identification, 985 instance and class variables, 252 Java jack = new Human(), 227 Destination.java, 995 keyword, 269 JVM, 994 local variable modifications, 994 definition, 260 native2ascii tool, 995 keyword, 272–273 Source.java file, 995 m1() method, 262–263 Test.java, 994 rules, 260–263 non-negative integers, 985–986 main() method, 223, 267 UCS methods, 224, 264–265 BMP, 991 add method, 256–257 definition, 992 declarations and signatures, 257 four-dimensional structure, 991 definition, 255 octet, 991 instance and class, 264–265 UCS-2, 992 printPoem method, 259–260 UCS-4, 992 return statement, 258–260 UTF-8, 993 return type, 256 UTF-16, 992 signature, 257 Character formatting, 657–658 throws clause, 256 Character literals, 124 m1() method, 274 charValue() method, 446 nested class, 224 Checked and unchecked exceptions, 476 null type, 228, 252 CatchNonExistentException class, 482 objects, 223, 224 default constructor, 485 printNum() instance method, 271 exceptional conditions, 475 printNum() method, 272, 273 instance initializer, 484 single-static-import declaration, 250 java.io.IOException, 475 static import declaration248–250 m1() method, 477–478 static-import-on-demand readChar() method, 475 declaration, 250 ReadInput class, 476 Student class, 273 ReadInput.readChar() Test class, 251 method, 474, 480, 481 top-level class, 251 ReadInput2Test class, 480 type search order, 241–246 static initializer, 484 Class loader, 399 System.in.read() method, 474, 477 Class variables, 226 System.out.println() method, 474 Clock class throws clause, 478, 479 now() method, 588 Civic LX model, 311 systemUTC() method, 588 ClassAccessTest class, 233 tick() method, 589 Classes and objects tickXxx() methods, 589 access level modifiers, 233–236 clone() method automatic import declarations, 247–248 CloneNotSupportedException, 415 Beginning Java 9, 224 container object, 417–418 creating instances, 226–228 declaration, 414 declaration, 224–225 DeepClone class, 420, 421 single-line comment, 48 DoubleHolder class, 415–417 default initialization, 232–233 ShallowClone class, 418–420 definition, 223 close() method, 505 dot notation, 229–232 Code point, 985 field declaration, 225–226 Coercion polymorphism, 28–29

1025 ■ INDEX

Comparable interface Coordinated Universal Time (UTC), 554 ComparablePerson class, 881–882 copyOf() method, 712, 748 ComparablePerson objects, 883–885 copyOf() static method, 711 compare() method, 883 copyOfRange() method, 714, 748 compareTo() method, 880 Counter, 553 equals() method, 883 NullPointerException, 885 Test class, 882–883 „„ D thenComparing() default method, 884 Data types thenComparing() method, 885 binary numbers, 125 Compiled code, 3 built-in data types, 99 Compile-time errors, 13 definition, 99 concat() method, 543 identifier, 100–101 Constructors integers, 103 access level modifier, 333–336 Java, 102–106 compile-time error, 792 compiler, 123–124 CSub class, 790 language, 100 CSuper class, 790 jdojo.datatype module, 125–126 CTest class, 790 keywords, 102 declaration, 323–325 little-endian and big-endian, 140–141 default, 337, 351 memory state, 103–104 Employee class, 788 primitive, 99 explicitly/implicitly, 795 String object, 105–106 final keyword in numeric literals, 123 blank final variable, 342 Unicode , 123–124 class variables, 346 user-defined, 99 compile-time vs. runtime variables, 103–105 final variables, 347 Date formatting, 665–667 instance variable, 343–345 Date-Time API local variables, 342–343 adjust date and time parameters, 343 Custom Date Adjuster, 598 reference variables, 346–347 ofDateAdjuster() method, 597 variable declaration, 341 TemporalAdjusters class, 595, 596 generic class, 347–350 atXxx() method, 562 instance initialization block, 338–339 calendar systems instance initializer, 351 Julian calendar, 556–557 int parameter, 330 ISO-8601 standards, 552, 558 Manager2 class, 794 classes, interfaces, memory allocation, 790 and enums, 560 NoSubclassingAllowed class, 795 Clock class, 587–589 overloading, 326–327 date construction, 551–552 package-level access, 795 DateTimeFormatter class (see DateTime parameterized classes, 351 Formatter class) return statement, 332 Daylight Savings Time, 551 rules, 330 design principles, 550 SmartDog class, 327–329, 331 Duration class, 563 static initialization block, 339–341 from() method, 560–561 string argument, 791, 793 getXXX() method, 561 superclass, 791, 796 Instant class, 563–564 Test class, 331 legacy, 550 Continue statement, 217, 218 LocalDate class, 551 Control flow statement, 193 machine-scale timeline, 563 Conversion characters minusXXX() method, 562 character formatting, 657–658 multipliedBy(), dividedBy(), and negated() numeric formatting, 658–660 methods, 562

1026 ■ INDEX

non-ISO calendar systems, 605–606 Default constructor, 337 now() method, 551 Default methods declarations ofXXX() methods, 560 vs. concrete method, 843 parsing dates and times Named interface, 843 from() method, 619 DEFAULT , 971 getErrorIndex() method, 618 Dereferencing, 296 parse() method, 618–619 Descendants, 759 parseBest() method, 620 Digital Versatile Disc (DVD), 17 partials dividedBy() method, 562, 566 LocalDate, 594–595 divide() method, 1005 using Year, YearMonth, Documentation comments and MonthDay, 593–594 block and inline tags periods, 589–591 @author tag, 1001 computations, 590 {@code }, 1006 normalized() method, 590 contexts, 1000 static factory methods, 589 definition, 999, 1021 between two dates and times, 591 @deprecated tag, 1001 plusXXX() method, 562 {@docRoot}, 1006 problems, 550 @exception tag, 1001 querying Datetime objects @hidden tag, 1009 CustomQueries class, 603 @index inline tag, 1009 TemporalQueries class, 601–602 {@inheritDoc} tag, 1006–1007 TemporalQuery interface, 602 {@linkplain} tag, 1008 toLocalTime() method, 605 {@link} tag, 1008 timekeeping {@literal }, 1008 apparent solar time, 553 overview comment, 1000 counter, 553 @param, 1002 frequency standard, 553 @provides tag, 1010 international atomic time, 553 @return tag, 1002 time scale, 552 @ (see tag, 1002) time zones/Daylight Savings Time, 555 @serialData tag, 1004 UT1, 553 @serialField tag, 1004 UTC, 554 @serial tag, 1003 time zone conversion, 587 @since tag, 1005 toString() method, 564 @throws tag, 1005 toXXX() methods, 561 @uses tag, 1010 withXXX() method, 561 {@value} tag, 1008, 1009 ZonedDateTime class, 551, 584 @version tag, 1006 DateTimeFormatter class Calc class, 997, 1012 DateTimeFormatterBuilder class, 617–618 HTML frames, 1017, 1019 format() method, 607, 609–610 HTML tags, 998 locale specific formats, 615–617 javadoc tool, 997–998 non-letter characters, 610 <@args-file-paths>, 1015 ofPattern() method, 610 @author and @version tags, 1016 optional section, 613 generation, 1017 predefined formatters, 607–608 , 1015 StringBuilder, 607 overview.html file, 1015 symbols, 611 searching, 1019–1020 use patterns, 614–615 overview comment, 1012 withLocale() method, 610 package.html file, 1011 Daylight Savings Time, 551, 555 package-info.java file, 1011 Debugging, 13 packages, 1010 Declaration statement, 192 source files processing, 1012 Declarative paradigm, 7 types, 998 Deep cloning, 418 unprocessed files, 1012

1027 ■ INDEX

Dot notation, 229–232 Throwable class, 488 Duplicate modules, 78–80 class hierarchy, 469 Duration class, 565 definition, 464 categories, 565 error checking, 462–463 creating, 563–564 error condition, 462 object, 563 finally block toDays() method, 566 closing brace, 490 toHours() method, 567 opening brace, 490 using instant and, 564, 565 sets of statements, 491 Dynamically linked libraries (DLLs), 35 try-catch-finally block, 491 try-finally blocks, 492 multi-catch block, 473 „„ E multiple catch blocks, 470 Eager evaluation, 305 pseudocode, 463 Empty statement, 205, 218–219 rethrowing, exception Enum types catch block, 494–495 associating a body, 905–907, 909 Exception type, 497 class type, 898 fillInStackTrace() method, 496 comparison, 910 original exception, 496 compile-time error, 899 RuntimeException setting, 495 constants, 899 throw statement, 494 data and methods, 903–905 too many exceptions, 497–498 DefectUtil class, 896 stack accessing gender, 897 LIFO style, 499 implement interfaces, 913–914 memory arrangement, 499 jdojo.enums module, 895 stack frames, 501 nested enum types, 911–913 thread frames, 499–500 ranges of enum constants, 914–915 throw statement, 485–486 reverse lookup, 914 transfer of control, 467–468 severity, 896–898 try-catch block, 464–467 superclass, 899–902 try-with-resources switch statements, 903 AutoCloseable resource class, 504 Ephemeris Time (ET), 553 close() method, 505 equalsIgnoreCase() method, 531 getSuppressed() method, 505, 506 equals() method, 430, 910 MyResource Object, 504 Account class, 409 Expression statement, 192–193 hashCode() method, 407 implementation, 405 non-null references, 409 „„ F null reference, 407 Fields Point class, 405 default initialization, 232–233 SmartCat class, 410 hiding SmartPoint class, 406, 408 FHidingSub class, 799 Test class, 408 FHidingSuper class, 799, 801, 802 unique identity, 404, 435 fill() method, 748 Equinox, vernal, 556 Finally block statement, 490–494 eval() method, 976 Fixed-point number format, 118 Float data type, 118–120 abnormal condition, 462 Floating-point format, 118 checked and unchecked exceptions (see Floating-point numbers Checked and unchecked exceptions) denormals, 136 class creation formatting, 661–663 MyException class, 486 NaN, 135 printStackTrace() method, 488–489 signed infinities, 134 stack trace, 488–489 signed zeros, 134

1028 ■ INDEX

Float literals, 118–119 LocalDate objects, 577–579, 581–582 Foreach loop, 291 LocalDateTime class, 577–579, 581 Formal parameters, 257 LocalTime class, 577–579, 581–582 format() method, 640, 644–645 month enum, 573–574 Format specifier, 647–648 offset time and datetime, 582–583 explicit indexing, 650 TemporalUnit interface, 576 list of valid flags, 652 ZonedDateTime class, 583–585, 587 relative indexing, 650–651 ZoneId class (see ZoneId class) format() static method, 644 ZoneOffset class, 568–569 Formatting data, jdojo.format module, 631 HyperText Markup Language (HTML), 12 Formatting dates DateFormat class, 632 formatting symbols, 636 „„ I GregorianCalendar class, 636 IEEE floating-point exceptions java.util.Locale class, 632 division by zero, 138 parse() method, 637 inexact, 139 ParsePosition object, 637–638 invalid operation, 138–139 SimpleDateFormat class, 635 Java implementations, 140 styles, 632 overflow, 139 time parts, 638–639 parameters, 140 Formatting numbers underflow, 139 DecimalFormat class, 641 if-else statement NumberFormat class, 639 Boolean type, 198 Functional interface, 880 calc() method, 199 Functional paradigm, 8 flow diagram, 196 Imperative paradigm, 6 Implicit dependence „„ G java.base module, 368 Generics, 347–350 jdojo.person.test module, 368–371 getArea() method, 808 module graph, 372 getErrorIndex() method, 618 requires statement, 368 getId() method, 273, 1007 transitive modifier, 371 getSuppressed() method, 505 Inclusion polymorphism, 29–30 getXXX() method, 561 Inheritance, 25 Glyph, 985 abstract classes and methods, 803–811 Google Chrome, 12 ancestors, 759 Gregorian calendar, 557–558 classes, 756–759 GregorianCalendar object, 624–625, 636 definition, 755 groupCount() method, 682 disabling, 802–803 group() method, 683 employee class, 757 generic method signatures, 811–812 getName() and setName() methods, 755, 817 „„ H immediate superclass, 760 hashCode() method, 749 instanceof operator, 766–768 , 400, 435 is-a, has-a, and part-of relationships, 759, Hijrah calendar system, 606 814–816 24-hour timekeeping system, 558 manager class, 758–759 Human jack, 227 object class, 759 Human-scale time object-oriented programming, 756 ChronoField fields, 574–575 objects, 755 ChronoUnit enum, 576–577 Singer and Employee classes, 817 components, 568 subclass, 756 DayOfWeek enum, 574 superclass, 756 last day of each month, 580–581 typo danger, 813–814

1029 ■ INDEX

Inheritance (cont.) player interface, 864 upcasting and downcasting singer interface, 864 client code, 762 SingerPlayer interface, 867 compile-time checks, 765 SingerWriter interface, 866–867 compile-time type, 762 superinterfaces, 865 “is-a” relationship, 762 writer interface, 864 PartTimeManager, 765 inheriting conflicting implementations printName() method, 764 "class must override the conflicting printName() static method, 763 method" rule, 874 setName() and getName() methods, 762 superclass, 871–873 subclass variable, 764 superinterface, 873–874 test class, 764 instanceof operator typecast, 765 class diagram, 876 Inner class, 337 compile-time type, 876–877 Instance method, 264–265 Munificent interface, 877–878 Instance variables, 226 StingyGiver class, 878 Instant class, 564, 565 jdojo.interfaces Module, 823 Integers letDucksWalk() method, 827–828 bits, 126 letThemWalk() method, 825, 827, 828 byte/octet, 126 marker interface, 879 decimal equivalent, 127 members decimal-to-binary conversion, 126 abstract methods declarations, 837–838 diminished radix complement, 127–128 constant fields declarations, 834–836 long and double data types, 126 default methods declarations, 839–844 MSB and LSB, 127 private methods, 844–846 radix complement, 128–129 static methods declarations, 838–839 Integrated development environments (IDEs), 13 new reference type Interfaces Choices interface, 850 Animal class, 828 instance/static variable, 851 Cat class, 832 Swimmable interface, 848–850 Comparable interface (see Comparable interface) variable type, 848, 850–851 declaration, 833–834 polymorphism Duck class, 825 Turtle class declaration, 887 dynamic binding, 889–890 Turtle object, 888 Fish class, 828 Turtle view, 888 functional interface, 880 Walkable view, 888–889 implementation Revised Duck class, 829 Banker interface, 855–856 Revised Person class, 829 class declaration, 851 Revised Walkables class, 831 Fish class, 852–853 superinterface-subinterface relationship, 870 hilda variable, 855 supertype-subtype relationship, 863 overriding method, 858 Test class, 831 partial interface, 861, 863 Walkable interface, 829 specification, 851 Walkables class, 825–827, 830 static methods, 852 walkMe() method, 827 swim() method, 852 walk() method, 824, 825, 830 Swimmable interface, 852, 854–855 intern() method, 529 UnstablePredictableBank class, 857 International Air Transport Association (IATA), 572 withdraw() and deposit() methods, 856–857 International Atomic Time (TAI), 553–554 inheritance International Bureau of Weights and Measures CharitySinger interface, 865 (BIPM), 553 CharitySingerPlayer interface, 867 International Earth Rotation Service (IERS), 554 conflicting method overriding, 868–869 Invoking a method, 258, 265–266 Melodist class, 866–867 isEmpty() method, 873

1030 ■ INDEX isLetter() and isDigit() methods, 445 , 47 ISO-8601 standards for datetime, 552 verification, JDK Installation, 37 components, 558 Java Runtime Environment (JRE), 34 duration, 559 Java shell 24-hour timekeeping system, 558 architecture, 923–924 partials, 558 auto-completion, 950–953 toString() methods, 559 command, 925 zone offset, 559 custom feedback modes, 965–969 isValidAmount() method, 286 documentation, 972–973 Iterator, 716–717 editing snippets, 935–936 evaluating expressions, 929–931 execute/evaluate snippet, 926 „„ J execution environment, 948–949 Java Archive (JAR file), 47 exiting tool, 927 javac compiler, 95 feedback mode, 962–964 Java Development Kit (JDK), 34 import statements, 940–943 Java program, 12 JDK 9, 922–923 application, 46 JShell command-line tool, 922 bytecode, 47, 60, 92 listing snippets, 931–934 class declaration, 54–56, 58–59 method declarations, 944–945 command-line options, 80–81 no checked exceptions, 950 compilation unit, 51 reloading, 958–960 compiling, source code, 60–62 REPL, 922 components, 94 rerunning previous snippets, 937 declaration, module, 49–51 resetting, 958 definition, 46 /save command, 956 description, module, 71–72 snippets and commands, 927–928 documentation comment/javadoc editor, 961–962 comment, 49 history, 954 duplicate modules, 78–80 stack trace, 955–956 fully qualified name, 59 startup snippets, 969–972 implementation, 93 System.out.println() method, 926 import declarations, 53–54 type declarations, 945–948 javac, 95 shell, 922 Java package, 62–64 variable declarations, 937–940 JDK 9, 33 Java virtual machine (JVM), 3, 12, 60, JDK directory structure, 34–36 92, 267–269 JShell Tool, 38, 46 JDK 9, 33 JVM specification, 91, 93 JShell API legacy mode, 75–77 creation, 975 limit modules, 70–71 handling snippet events, 978–982 listing observable modules, 69–70 jdk.jshell module, 974 main() method, 73 Snippet class, 976–977 module descriptor, 73–74 SnippetEvent interface, 974 module path, 78–79 SourceCodeAnalysis class, 974 multi-line comment, 49 use case diagram, 974 NetBeans 9, 38–39, 41–42 JShell Edit Pad, 935 package declaration, 52–53 JShell Tool, 38 printing module resolution, 72–73 Julian calendar, 556, 558 running, 64–69 Just-in-time compilers (JIT), 3 simple name, 59 single-line comment, 48 system requirements, 33 „„ K source code, 47–48 kverbose, 965

1031 ■ INDEX

„„ L Modular compilation unit, 356 Module dependence Last-in, first-out (LIFO), 499 empty package error, 366 Lazy evaluation, 305 jdojo.address module, 360–364, 366 Leap years, 557 jdojo.person module, 360–364, 366 Legacy datetime classes module not found error, 367 add() method, 623 module resolution exception, 367–368 Calendar class, 622–623 package does not exist error, 367 conversion between datetime and, 626 troubleshooting, 366 convert to Date to Instant, 626–627 Module-friendly exports, 358 convert to GregorianCalendar to new Module graph, 65 Datetime, 627 Module path, 78–79 date class, 621 Modules roll() method, 624–625 aggregator module, 384, 392 Legacy mode, 75–77 automatic modules, 379–382, 391 letThemWalk() method, 838 declaration Little-endian, 140 modular compilation unit, 356 LocalDate class, 954 module directives, 357 Logic errors, 13 module statements, 357 Logic Paradigm, 8 ordinary compilation unit, 356 Lunar calendar, 556 definition, 355 Lunisolar calendar, 556 disassemble class files, 388–391 exporting, 358 „„ M exports statement, 391 getClass() method, 384 Machine-scale timeline, 563 getModule() method, 385 Marker interface, 879 java.base module, 359 Metacharacters, 670, 672 JDK 9, 386–387 Method hiding JDK 9 designers, 377 MHidingSub class, 798 jdojo.claim module, 359, 360 MHidingSuper class, 796–798 jdojo.mod module, 385 static methods, 797 jdojo.policy module, 358, 360 Method overloading module-friendly exports, 358 Adder class, 788 ModuleInfo class, 386 and method overriding, 785 named module, 391 OME1 class, 784 normal modules, 379 overloaded add() method, 788 opening modules and packages, 373–376, parameters, 788 379, 391 polymorphism, 786 optional dependence, 373 test program, 786–788 qualified exports, 358 Method overriding requires statement, 359 access levels, 778 restrictions, 377 AOSuper class, 782–783 splitting packages, 376–377 checked exception, 779 static modifier, 359 class declarations, 775–776 transitive modifier, 359, 391 class definitions, 779 types, 378 EmpNotFoundException, 780 unnamed modules, 383, 391 getEmp() method, 779, 781 unqualified export, 358 method declaration, 782 Multi-catch block, 473 parameter, 777 Multi-dimensional array, 703 print() method, 776–777 data element, 730 static methods, 777 elements, 732, 734 Microsoft Internet Explorer, 12 initialization, 734–735 minusXXX() method, 562 memory state, 731 Modular, 63 ragged array, 732–733

1032 ■ INDEX

Multi-line comment syntax, 124 hashCode() method, 401, 435 Multiple interfaces implementation, 401–402 Adder and Subtractor, 858 instance variables, 404 ArithOps class, 858 Java, 401 class declaration, 858 piece of information, 400 Turtle class, 859–861 process, 400 walk() method, 859 hash() method, 431 multipliedBy() methods, 562 immutable class multiplyUnsigned() method, 448 advantages, 424 MyException class, 486, 487 copy constructor, 429 getIntHolder() method, 428 getValue() and getHalfValue() „„ N methods, 426 Name hiding, 263 halfValue instance variable, 426 negated() methods, 562 internal and external state, 424 Nested class, 337 IntHolder class, 424–425 Nested type declaration IntHolderWrapper class, 427–428 ATMCard interface, 846 IntWrapper class, 425 definition, 846 String class, 426 Job interface, 847–848 value instance variable, 425 NetBeans, 946 isNull() method, 432 NetBeans 9, 38–39, 41–42 java.lang package, 395 NetBeans IDE nonNull() method, 432 creation, Java project, 81–88 reference variable, 396–397 directory structure, 89 reimplement method, 397 modular JARs, 88 requireNonNull(T obj) method, 432 module classes, 89 string representation open command, 91 null reference, 414 project properties, 89–91 Point class, 412, 413 No-args constructor, 337 pt reference variable, 413, 414 Non-ISO calendar systems, 605 SmartIntHolder class, 411–412 Non-static methods, 264 toString() method, 410, 411, 413, 435 Not-a-Number (NaN), 119, 135 valueOf() static method, 411 Null type, 228 Test class, 433 NumberFormatException method, 444, 445 toString() method, 398, 433 utility methods, 433 Object-oriented (OO) paradigm, 9–12 „„ O Object-oriented programming, 283, 347 Object class Observable modules, 65 binary class format, 399 OffsetTime and OffsetDateTime ClassLoader class, 399 classes, 582 clone() method (see clone() method) ofXxx() methods, 560 compare() method, 430 Operators, 145 deepEquals() method, 430 arithmetic, 150 equals() method (see equals() method) modulus operator (%), 157–159 finalize() method addition (+), 151–153 declaration, 422 compound arithmetic assignment source code, 422, 436 operators, 160–161 Test class, 423 increment and decrement, 161–164 getClass() method, 399, 435 subtraction (–), 153–154 hash code unary minus operator, 159 Book class, 403 unary plus operator, 159 data retrieval, 401 assignment, 147–149 definition, 400 binary, 145 equals() method, 404 bitwise, 180–184

1033 ■ INDEX

Operators (cont.) variable components, 295 boolean logical operators, 174–175 variable vs. reference variable, 296 compound boolean logical assignment , 30 operators, 179 parse() method, 637, 642 logical AND operator (&), 177 Partials, 551, 558 logical NOT operator (!), 175–177 PartTimeManager, 765 logical OR operator (|), 178 plusXXX() method, 562 logical short-circuit OR operator (||), 178 Polar motion, 553 declaration, initialization, and assignment, 149 Polymorphism, 26, 887 precedence, 184–185 Post-fix increment operator, 162 relational, 169 Pragmatics, 4 boolean logical operators, 179 Pre-fix increment operator, 162 equality, 169–172 Primitive data types greater than operator (>), 172–173 , 117 greater than or equal to operator (>=), 173 byte data type, 112–113 inequality, 172 char data type, 114 less than operator (<), 173–174 character escape sequence, 115 less than or equal to operator (<=), 174 double data type, 121–122 string concatenation operator, 164–169 float data type, 118–120 ternary, 145–146, 180 floating-point data types, 118 types, 145 int data type, 108–109 unary, 145 integral, 108 Ordinary compilation unit, 356 long data type, 110–111 Overloaded constructors, 326 numeric data type, 107 Overloading polymorphism, 27–28 character escape sequence, 115–117 short data type, 113–114 unicode character escape sequence, 115 „„ P printf() method, 648 Parameterized classes, 348 Printf-style formatting Parameter passing mechanisms close() method, 645 Car class (see Car class) conversion characters (see Conversion idRef, 296 characters) pass by constant reference value, 304 C’s, 643–644 pass by constant value, 299, 313 format()/printf() method, 644, 645 pass by name, 305 format specifier (see Format specifier) pass by need, 306 format() static method, 644 pass by reference, 303, 315, 317 format string, 646–647 actual and formal parameters, 300 java.util.Formatter class, 643 advantages, 302 System.out.print() methods, 644 definition, 299 toString() method, 644 disadvantages, 303 toString() method, 645 getNumber() method, 302 println() method, 193 increment() method, 300 printM() method, 265 swap() method, 301 printMN() method, 265 pass by result, 304 printNum() method, 273 pass by value, 313 printPoem method, 259 actual and formal parameters, 296 Procedural paradigm, 6 advantages, 299 Programming language disadvantages, 299 abstraction, 14–15 increment() method, 297 hiding complexities, 15–20 result, 304 by specification, 19 smartIncrement() method, 298 assembler, 2 swap() method, 298 coercion polymorphism, 28–29 , 306 compiled code, 3 reference variable, 296 components, 4

1034 ■ INDEX

data abstraction, 20–23 Matcher object, 692 data and algorithm, 6 Pattern object, 692 declarative paradigm, 7 StringBuffer object, 692 encapsulation and information hiding, 23–25 groups and back referencing, 682–687 English-German translator, 1 Matcher class, 674 functional paradigm, 8 creation, 676 getRangeSum procedure, 18–20 end() method, 676–677 higher-level programming language, 2, 3 find() method, 676 human-to-computer communication, 1 group() method, 677 human-to-human communication, 1 start() method, 676–677 imperative paradigm, 6 metacharacters, 670, 672 inclusion polymorphism, 29–30 matches() method, 670 inheritance, 25–26 named groups Java, 12 back reference, 688 JVMs, 3 find() method, 689 logic paradigm, 8 group name, 688 machine code, 1 replacement text reference, 688 machine language, 1–2 Pattern class, 674 medium of communication, 1 PatternSyntaxException class, 674 object-oriented (OO) paradigm, 9–12 quantifiers, 680 overloading polymorphism, 27–28 replaceAll() method, 671 parameterization, 17 replaceFirst() method, 672 parametric polymorphism, 30 reset() method, 690 polymorphism, 26–27 Relational operators, 169 procedural paradigm, 6 equality operator, 169–172 programmer, 1 greater than operator (>), 172–173 programming paradigm, 5 greater than or equal to operator (>=), 173 source code, 3 inequality operator, 172 Proleptic Gregorian calendar, 557 less than operator (<), 173–174 less than or equal to operator (<=), 174 replaceAll() method, 685 „„ Q return statement, 258–259 Qualified exports, 358 roll() method, 624–625 Qualified names, 100 Rounding modes negative infinity, 137 positive infinity, 137 „„ R rounding toward nearest, 138 Read-Eval-Print loop (REPL), 922 rounding toward zero, 137 Ragged array, 732 Runtime errors, 13 ReadInput class, 476 RuntimeException class, 475 ReadInput2.readChar() method, 481 ReadInput.readChar() static method, 476 ReadInput2Test2.main() method, 481 „„ S Reference variable, 295 Semantics, 4 Reflection, 373 setAll() method, 748 Shallow cloning, 417 , 679–680 Short-circuit AND operator, 176 boundary matchers, 681–682 Short-circuit OR operator, 178 character class, 673–674 Signed right shift operator, 183 definition, 669 Simple names, 100 e-mail validations, 691 Singleton pattern, 335 engine, 670 Solar calendar, 556 find-and-replace Solar day, 553 appendReplacement() method, 693–694 Source code, 3 appendTail() method, 694 sourceCodeAnalysis() method, 975

1035 ■ INDEX split() method, 535 palindrome, 538–539 Stack trace, 488–489 pool, 528–530 Statements splitting and joining, 535 break statement, 214–216 StringBuilder and StringBuffer, 539–543 continue statement, 217, 218 switch statement, 536–537 control flow, 193 Structured query language (SQL), 3, 7 declaration statement, 192 Subclass, 756 definition, 191 substring() method, 952 do-while statement, 212–214 subtractUnsigned() method, 448 empty statement, 218–219 Superclass expression, 192–193 access level modifier, 761 for-each statement, 209–210 Employee class, 760, 761 for statement getName() and setName() methods, 761 condition-expression, 206–207 immediate subclass, 760 empty statement, 205 public class member, 761 expression-list, 207–209 SystemProgrammer, 760 initialization, 205–206 switch statement, 536–537 null statement, 205 compile-time constant, 203 jdojo.statement, 191 data type, 202 while statement, 210–212 if-else statement, 203 static modifier, 264, 267 Symbols datetime format, 611–613 Static constructor, 338 Syntax, 4 Static factory methods, 585, 588 System.out.print() methods, 644 Static initialization block, 339–341 System.out.println() method, 248 String and System classes, 247 StringBuffer object, 539–543 StringBuilder object, 539–543 „„ T String literals, 124 Temps Atomique International scale, 553 escape sequence characters, 522–523 Ternary operator, 145, 180 multi-line string, 522 Terrestrial Dynamical Time (TDT), 553 unicode escapes, 523 test(int) method, 454 String objects, 708 test() method, 452, 453 String parameter, 326 Thai Buddhist calendar, 606 Strings ThisError class, 274 CharSequence, 523 Throwable class, 469, 488 comparison, 526–528 Thunk, 305 concatenation operator (+), 164–169, 543 Time formatting, 664–666 creation, objects, 523–524 Time zone, 555 definition, 521 rules, 555 language-sensitive string comparison, 543–544 toDays() method, 566 length() method, 524 toLowerCase() methods, 445 literals, 522 Top-level methods, 944 objects, 524–526 toString() method, 413, 559, 564, 718 operations toUpperCase() method, 445 case changes, 532 toXXX() method, 561 character, 530 trim() method, 533 empty, 531–532 True solar day, 553 endsWith() method, 534 Truncating duration, 567–568 equality, 531 Truncation or chop mode, 137 replacing part, 533–534 TZDB, 572 representing values, 532 searching, 532 startsWith() method, 534 „„ U substring() method, 533 Unary operator, 145 trimming, 533 Unboxing, 449–451

1036 ■ INDEX

Uncaught exception, 465 Character class, 440, 445–446 Unchecked exceptions, 476 collections, 457 Unified Modeling Language (UML), 759 comparison operations, 455–457 Universal character set (UCS) constructor, 442 BMP, 991 definition, 439 definition, 992 equals() method, 442 four-dimensional structure, 991 integer object, 441 octet, 991 jdojo.wrapper module, 439 UCS-2, 992 null values, 452 UCS-4, 992 numeric UTF-8, 993 BigDecimal and UTF-16, 992 BigInteger classes, 445 Universal polymorphism, 26 byteValue() method, 442 Universal Time (UT), 553 integer object and int value, 444 Universal Time Zero (UT0), 553 intValue() method, 442 Unnamed modules, 383 NumberFormatException, 444–445 UT0. See Universal Time Zero (UT0) parseInt() method, 444 UTC with Smoothed Leap Seconds (UTC-SLS), 554 numeric wrapper classes, 442–445 overloaded methods, 452–455 „„ V primitive types, 440 valueOf() method, 447 unsigned numeric operations, 447–449 Var-args method valueOf() methods, 441 aMethod(), 290 Write once, run anywhere (WORA), 12 arity, 288 arrays, 289 compute maximum integers, 292–293 „„ Y disadvantages, 290 System.arraycopy() method, 714 foreach loop, 291 length property, 291 main() method, 294 „„ Z max() method, 288, 291 Zero-based indexing, 704, 715 overload, 293 ZonedDateTime class, 940 Vernal equinox, 556–557 ZoneId class formats, 570 of() factory method, 570 „„ W, X time change rules, 571 withXxx() methods, 561 TZDB, 572 Wrapper classes Zone offset, 555, 559 autoboxing and unboxing, 449–455 ZoneOffset class, 568–569 Boolean class, 447 Zulu time, 554

1037