2016年6月8日星期三

Reading Notes : Core Java Tenth Edition -- Chapter 1. An introduction to Java

1.  The authors of Java have published a shorter summary that is organized along the following 11 buzzwords:
Simple, Object-Oriented, Distributed, Robust, Secure, Architecture-Neutral, Portable, Interpreted, High-Performance, Multithreaded, Dynamic

http://horstmann.com/corejava/java-an-overview/7Gosling.pdf

2.  The syntax for Java is a cleaned-up version of the syntax for C++ and the size of the basic interpreter and class support is small.

3.  Java has a pointer model that eliminates the possibility of overwriting memory and corrupting data.

4.  Java was designed to make certain kinds of attacks impossible, among them:
    a)    Overrunning the runtime stack—a common attack of worms and viruses
    b)    Corrupting memory outside its own process space
    c)    Reading or writing files without permission

5.  The Java compiler generates bytecode instructions which have nothing to do with a particular computer architecture. Rather, they are designed to be both easy to interpret on any machine and easily translated into native machine code on the fly.

6.  Virtual machines have the option of translating the most frequently executed bytecode sequences into machine code—a process called just-in-time (JIT) compilation.

7.  There are no “implementation-dependent” aspects of the specification. The sizes of the primitive data types are specified, as is the behavior of arithmetic on them.

8.  Java delivered a simple toolkit that provided common user interface elements on a number of platforms.

9.  The just-in-time compilers have become so good that they are competitive with traditional compilers and, in some cases, even outperform them because they have more information available. For example, a just-in-time compiler can monitor which code is executed frequently and optimize just that code for speed. A more sophisticated optimization is the elimination (or “inlining”) of function calls. The just-in-time compiler knows which classes have been loaded. It can use inlining when, based upon the currently loaded collection of classes, a particular function is never overridden, and it can undo that optimization later if necessary.

10.  On the downside, thread implementations on the major platforms differ widely, and Java makes no effort to be platform independent in this regard. Only the code for calling multithreading remains the same across machines; Java offloads the implementation of multithreading to the underlying operating system or a thread library.

11.  If you want to use Java in embedded systems, you need a different license and will likely need to pay royalties.

Reading Notes : Core Java Tenth Edition -- Chapter 2. The Java Programming Environment

1.  After you are done installing the JDK, you need to carry out one additional step: Add the jdk/bin directory to the executable path—the list of directories that the operating system traverses to locate executable files:
    a)    In UNIX (including Linux, Mac OS X, and Solaris), the procedure for editing the executable path depends on the shell you are using. If you use the Bourne Again shell (which is the Linux default), then add a line such as the following to the end of your ~/.bashrc or ~/.bash_profile file:
export PATH=jdk/bin:$PATH
    b)    Under Windows, log in as administrator. Start the Control Panel, switch to Classic View, and select the System icon. In the system properties dialog, click the Advanced tab, then click on the Environment button. Scroll through the System Variables window until you find a variable named Path. Click the Edit button. Add the jdk\bin directory to the beginning of the path, using a semicolon to separate the new entry, like this:
jdk\bin;other stuff

2.  The src.zip file contained in jdk has the source code for all public libraries. To obtain even more source (for the compiler, the virtual machine, the native methods, and the private helper classes), go to http://jdk8.java.net.

3.  The documentation is contained in a compressed file that is separate from the JDK. You can download the documentation from www.oracle.com/technetwork/java/javase/downloads.

4.  You can download the Core Java Program from http://horstmann.com/corejava.

5.  The javac program is the Java compiler. It compiles the .java file into the .class file. The java program launches the Java virtual machine. It executes the bytecodes that the compiler placed in the class file. The compiler requires a file name (Welcome.java). When you run the program, you specify a class name (Welcome) without a .java or .class extension.

6.  appletviewer is a special tool included with the JDK that lets you quickly test an applet. You need to give this program an HTML file name, rather than the name of a Java class file. The applet viewer has no capabilities to send mail or display a web page, and it ignores all HTML tags except for the applet tag.

7.  Many browsers do not have Java support enabled by default. The page http://java.com/en/download/help/enable_browser.xml shows how to set up the most common browsers for Java.

8.  You can temporarily configure Java to trust applets from the local file system. First, open the Java control panel.
• In Windows, look inside the Programs section of the control panel.
• On a Mac, open System Preferences.
• On Linux, run jcontrol.
Then click the Security tab and the Edit Site List button. Click Add and type in file:///. Click OK, accept another security prompt, and click OK again.

2016年6月2日星期四

Reading Notes : Core Java Tenth Edition -- Chapter 3. Fundamental programming structures in Java

1.  Java is case sensitive.

2.  The rules for class names in Java are quite generous. Names must begin with a letter ( or dollar sign), and after that, they can have any combination of letters and digits.

3.  You need to make the file name for the source code the same as the name of the public class in that file, with the extension .java appended.

4.  To run a compiled program, the Java virtual machine always starts execution with the code in the main method (exactly same as public static void main(String[] ) )  in the class you indicate. The Java launcher in Java SE 1.4 and beyond enforces that the main method is public.

5.  If the main method exits normally, the Java program has the exit code 0, indicating successful completion. To terminate the program with a different exit code, use the System.exit method.

6.  Java is a strongly typed language. Every variable must have a declared type. In Java, the sizes of all numeric types are platform-independent. Java does not have any unsigned types. (except char which is taken as a character type)

7.  0.125 = 2-3 can be written as 0x10p-3 . In hexadecimal notation, you use a p , not an e (An e is a hexadecimal digit.), to denote the exponent. Note that the mantissa is written in hexadecimal and the exponent in decimal. The base of the exponent is 2, not 10.

8.  Starting with Java 7, you can write numbers in binary, with a prefix 0b. For example, 0b1001 is 9. Also starting with Java 7, you can add underscores to number literals, such as 1_000_000 (or 0b1111_0100_0010_0100_0000) to denote one million. The underscores are for human eyes only. The Java compiler simply removes them.

9.  The constants Double.POSITIVE_INFINITY , Double.NEGATIVE_INFINITY , and Double.NaN (as well as corresponding Float constants) represent these special values, but they are rarely used in practice. x == Double.NaN is never true. All “ not a number ” values are considered distinct. However, you can use the Double.isNaN method: Double.isNaN(x) checks whether x is "not a number".

10.  There is no precise binary representation of the fraction 1/10, just as there is no accurate representation of the fraction 1/3 in the decimal system. System.out.println(2.0 - 1.1) prints 0.8999999999999999, not 0.9. If you need precise numerical computations without roundoff errors, use the BigDecimal class.

11.  Unicode code units can be expressed as hexadecimal values that run from \u0000 to \uFFFF . For example, \u2122 is the trademark symbol ( ™ ) and \u03C0 is the Greek letter pi ( π ).

12.  You can use these escape sequences inside quoted character constants and strings, such as '\u2122' or "Hello\n" . The \u escape sequence (but none of the other escape sequences) can even be used outside quoted character constants and strings. For example, public static void main(String\u005B\u005D args) is perfectly legal. \u005B and \u005D are the encodings for [ and ] . Unicode escape sequences are processed before the code is parsed. For example, "\u0022+\u0022" is not a string consisting of a plus sign surrounded by quotation marks (U+0022). Instead, the \u0022 are converted into " before parsing, yielding ""+"".  A comment // Look inside c:\users yields a syntax error because the \u is not followed by four hex digits.

13.  In Java, the char type describes a code unit in the UTF-16 encoding.

14.  You cannot convert between integers and boolean values.

15.  A variable name must begin with a letter and must be a sequence of letters or digits. Note that the terms “ letter ” and “ digit ” are much broader in Java than in most languages. A letter is defined as 'A' – 'Z', 'a' – 'z', '_', or any Unicode character that denotes a letter in a language. Similarly, digits are '0' – '9' and any Unicode characters that denote a digit in a language. If you are really curious as to what Unicode characters are “ letters ” as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.

16.  A char value, represents Basic Multilingual Plane (BMP) code points, including the surrogate code points, or code units of the UTF-16 encoding. An int value represents all Unicode code points, including supplementary code points. The lower (least significant) 21 bits of int are used to represent Unicode code points and the upper (most significant) 11 bits must be zero. Unless otherwise specified, the behavior with respect to supplementary characters and surrogate char values is as follows:
    - The methods that only accept a char value cannot support supplementary characters. They treat char values from the surrogate ranges as undefined characters. For example, Character.isLetter('\uD840') returns false, even though this specific value if followed by any low-surrogate value in a string would represent a letter.

    - The methods that accept an int value support all Unicode characters, including supplementary characters. For example, Character.isLetter(0x2F81A) returns true because the code point value represents a letter (a CJK ideograph).

17.  After you declare a variable, you must explicitly initialize it by means of an assignment statement — you can never use the values of uninitialized variables.

18.  const is a reserved Java keyword, but it is not currently used for anything. You must use final for a constant.

19.  The / operator denotes integer division if both arguments are integers, and floating-point division otherwise. Integer division by 0 raises an exception, whereas floating-point division by 0 yields an Infinite or NaN result.

20.  Some processors use 80-bit floating-point registers. These registers yield added precision in intermediate steps of a computation. By default, virtual machine designers are now permitted to use extended precision for intermediate computations. However, methods tagged with the strictfp keyword must use strict floating-point operations that yield reproducible results. For example, you can tag main as: public static strictfp void main(String[] args) , then all instructions inside the main method use strict floating-point computations. If you tag a class as strictfp , then all of its methods use strict floating-point computations.

21.  When applied to boolean values, the & and | operators yield a boolean value. These operators are similar to the && and || operators, except that the & and | operators are not evaluated in “ short circuit ” fashion. That is, both arguments are first evaluated before the result is computed.

22.  >>> operator fills the top bits with zero, whereas >> extends the sign bit into the top bits. There is no <<< operator. The right-hand side argument of the shift operators is reduced modulo 32 (unless the left-hand side is a long, in which case the right-hand side is reduced modulo 64). For example, the value of 1 << 35 is the same as 1 << 3 or 8.

23.  The functions in the Math class use the routines in the computer's floating-point unit for fastest performance. If completely predictable results are more important than fast performance, use the StrictMath class instead. It implements the algorithms from the “ Freely Distributable Math Library ” fdlibm, guaranteeing identical results on all platforms. See http://www.netlib.org/fdlibm/index.html for the source of these algorithms. (Whenever fdlibm provides more than one definition for a function, the StrictMath class follows the IEEE 754 version whose name starts with an "e" .)

24.  The six solid arrows in the following figure denote conversions without information loss. The three dotted arrows denote conversions that may lose precision. Conversions in which loss of information is possible are done by means of casts. The syntax for casting is to give the target type in parentheses, followed by the variable name.

25.  When two values with a binary operator (such as n + f where n is an integer and f is a floating-point value) are combined, both operands are converted to a common type before the operation is carried out:

  •  If either of the operands is of type double, the other one will be converted to a double.
  • Otherwise, if either of the operands is of type float, the other one will be converted to a float.
  • Otherwise, if either of the operands is of type long, the other one will be converted to a long.
  • Otherwise, both operands will be converted to an int.


26.  Java does not have a comma operator. However, you can use a comma-separated list of expressions in the first and third slot of a for statement.

27.  Operators’ precedence table :
Operators
Associativity
[] . ()(method call)
Left to right
! ~ ++ -- +(unary) -(unary) ()(cast) new
right to Left
* / %
Left to right
+ -
Left to right
<< >> >>>
Left to right
< <= > >= instanceof
Left to right
== !=
Left to right
&
Left to right
^
Left to right
|
Left to right
&&
Left to right
||
Left to right
?:
right to Left
= += -= *= /= %= &= \= ^= <<= >>= >>>=
right to Left


28.  When you concatenate a string with a value that is not a string, the latter is converted to a string.

29.  The String class gives no methods that let you change a character in an existing string. Because you cannot change the individual characters in a Java string, the documentation refers to the objects of the String class as being immutable. You cannot change the value of a string, but you can change the contents of the string variable and make it refer to a different string. It would seem simpler to change the code units than to build up a whole new string from scratch. However if various strings are sitting in a common pool and string variables point to locations in the pool, when you copy a string variable, both the original and the copy share the same characters. So overall, the designers of Java decided that the efficiency of sharing outweighs the inefficiency of string editing by extracting substrings and concatenating.

30.  To test whether two strings are identical except for the upper/lowercase letter distinction, use the equalsIgnoreCase method.

31.  If the virtual machine would always arrange for equal strings to be shared, then you could use the == operator for testing equality. But only string constants are shared, not strings that are the result of operations like + or substring . Therefore, never use == to compare strings lest you end up with a program with the worst kind of bug — an intermittent one that seems to occur randomly.

32.  Java strings are implemented as sequences of char values. the char data type is a code unit for representing Unicode code points in the UTF-16 encoding. The length method yields the number of code units required for a given string in the UTF-16 encoding.

33.  To get the true length, that is, the number of code points, call:
 int cpCount = greeting.codePointCount(0, greeting.length()); 


String.charAt(n) returns the code unit at position n. To get at the ith code point, use the statements:
   
int index = greeting.offsetByCodePoints(0, i); 

int cp = greeting.codePointAt(index);

34. If your code traverses a string, and you want to look at each code point in turn, use these statements:  

int cp = sentence.codePointAt(i); 

if (Character.isSupplementaryCodePoint(cp)) i += 2; 

else i++;  


the codePointAt method can tell whether a code unit is the first or second half of a supplementary character, and it returns the right result either way. You can move backwards with the following statements:

i--; 

int cp = sentence.codePointAt(i); 

if (Character.isSupplementaryCodePoint(cp)) i--; 



35.  Point your web browser to the docs/api/index.html subdirectory of your JDK installation, you will see the Java API documentation.

36.  The StringBuilder class was introduced in JDK 5.0. Its predecessor, StringBuffer , is slightly less efficient, but it allows multiple threads to add or remove characters. If all string editing happens in a single thread (which is usually the case), you should use StringBuilder instead. The APIs of both classes are identical.

37.  To read console input, you first construct a Scanner that is attached to System.in:

Scanner in = new Scanner(System.in) ; 


The nextLine method reads a line of input. To read a single word (delimited by whitespace), call next method. To read an integer, use the nextInt method. Similarly, the nextDouble method reads the next floating-point number.

38.Whenever you use a class that is not defined in the basic java.lang package, you need to use an import directive.

39.  The Scanner class is not suitable for reading a password from a console since the
input is plainly visible to anyone. Java SE 6 introduces a Console class specifically for this purpose. To read a password, use the following code:

Console cons = System.console(); 

String username = cons.readLine("User name: "); 

char[] passwd = cons.readPassword("Password: "); 


For security reasons, the password is returned in an array of characters rather than a string. After you are done processing the password, you should immediately overwrite the array elements with a filler value. Input processing with a Console object is not as convenient as with a Scanner . You can only read a line of input at a time. There are no methods for reading individual words or numbers.

40.  Java SE 5.0 brought back the venerable printf method from the C library:

41.  Each of the format specifiers that start with a % character is replaced with the corresponding argument. The conversion character that ends a format specifier indicates the type of the value to be formatted:



You can use the s conversion to format arbitrary objects. If an arbitrary object implements the Formattable interface, the object’s formatTo method is invoked. Otherwise, the toString method is invoked to turn the object into a string.

42.  You can specify flags that control the appearance of the formatted output. For example, the comma flag adds group separators. That is, System.out.printf("%,.2f", 10000.0 / 3.0) prints 3,333.33.
You can use multiple flags, for example, "%,(.2f ", to use group separators and enclose negative numbers in parentheses. All flags are as below:



43.  You can print the Date type by using a two-letter format, starting with t and ending in one of the letters in following table :


For example, System.out.printf("%tc", new Date()) prints the current date and time in the format: Mon Feb 09 18:05:19 PST 2004. The formatting of numbers and dates is locale specific. For example, in Germany, the group separator is a period, not a comma, and Monday is formatted as Montag.

44.  It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the %, and it must be terminated by a $:

System.out.printf("%1$s %2$tB %2$te, %2$tY", "Due date:", new Date())

prints Due date: February 9, 2004.
Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again:

System.out.printf("%s %tB %<te, %<tY", "Due date:", new Date())

prints Due date: February 9, 2004.

45.  You can use the static String.format method to create a formatted string without printing it:

String message = String.format("Hello, %s. Next year, you'll be %d", name, age); 

46.  To read from a file, construct a Scanner object from a File object, like this:

Scanner in = new Scanner(new File("myfile.txt")); 

 or

Scanner in = new Scanner(Paths.get("myfile.txt")); 


47.  When you specify a relative file name, the file is located relative to the directory in which the Java virtual machine was started.  if you use an integrated development environment, the starting directory is controlled by the IDE. You can find the directory location with this call:

String dir = System.getProperty("user.dir");  

48.  You can construct a Scanner with a string parameter, but the scanner interprets
the string as data, not a file name. For example, if you call

Scanner in = new Scanner("myfile.txt");

then the scanner will see ten characters of data: 'm', 'y', 'f', and so on.

49.  To write to a file, construct a PrintWriter object. In the constructor, simply supply the file name:

PrintWriter out = new PrintWriter("myfile.txt");

If the file does not exist, you can simply use the print , println , and printf commands as you did when printing to System.out .

50.  A block or compound statement is any number of simple Java statements that are surrounded by a pair of braces. Blocks define the scope of your variables. Blocks can be nested inside another block. You may not declare identically named variables in two nested blocks. A block allows you to have more than one (simple) statement in any Java programming structure that might otherwise have a single statement.

51.  The conditional statement in Java has the form

if (condition) statement [else statement] 
 
 The condition must be surrounded by parentheses. The else part is always optional. An else groups with the closest if .


52.  The while loop executes a statement while a condition is true. The general form is

while (condition) statement 
 
 The while loop will never execute if the condition is false at the outset.


53.
do statement while (condition);  

This loop executes the statement and only then tests the condition. It then repeats the statement and retests the condition, and so on.


54.  The for loop is a general construct to support iteration that is controlled by a counter or similar variable that is updated after every iteration:

for(statement;expression;statement)  statement; 

The first slot of the for statement usually holds the counter initialization. The second slot gives the condition that will be tested before each new pass through the loop, and the third slot explains how to update the counter. When you declare a variable in the first slot of the for statement, the scope of that variable extends until the end of the body of the for loop.


55.
switch (expression) 

{ 

    case option1: 

    statement; 

    break; 

 

    case option2: 

    statement; 

    break; 

 

. . . 

 

    default: 

    statement; 

    break; 

 

}  


Execution starts at the case label that matches the value on which the selection is performed and continues until the next break or the end of the switch . If none of the case labels match, then the default clause is executed, if it is present. It is possible for multiple alternatives to be triggered. If you forget to add a break at the end of an alternative, then execution falls through to the next alternative! Compiling your code with the -Xlint:fallthrough option will issue a warning message whenever an alternative does not end with a break statement. If you actually want to use the fallthrough behavior, tag the surrounding method with the annotation @SuppressWarnings("fallthrough"). Then no warnings will be generated for that method.

56.  A case label can be

  • A constant expression of type char, byte, short, or int
  • An enumerated constant
  • Starting with Java SE 7, a string literal
When you use the switch statement with enumerated constants, you need not supply the name of the enumeration in each label — it is deduced from the switch value.

57.  The break statement can also be used to break out of a loop. Java also offers a labeled break statement that lets you break out of multiple nested loops. The label must precede the outermost loop out of which you want to break. It also must be followed by a colon. You can apply a label to any statement, even an if statement or a block statement, like this:

label: 

{ 

. . . 

  if (condition) break label; // exits block 

. . . 

} 


// jumps here when the break statement executes 

Naturally, we don’t recommend this approach. Note, however, that you can only jump out of a block, never into a block.

58.  There is a continue statement that, like the break statement, breaks the regular flow of control. The continue statement transfers control to the header of the innermost enclosing loop. If the continue statement is used in a for loop, it jumps to the “update” part of the for loop. There is also a labeled form of the continue statement that jumps to the header of the loop with the matching label.

59.  In the java.math package: BigInteger and BigDecimal are classes for manipulating numbers with an arbitrarily long sequence of digits. The BigInteger class implements arbitrary precision integer arithmetic, and BigDecimal does the same for floating-point numbers. Use the static valueOf method to turn an ordinary number into a big number:

BigInteger a = BigInteger.valueOf(100); 

use methods such as add and multiply in the big number classes.

BigInteger c = a.add(b); // c = a + b 

BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); // d = c * (b + 2)  

60.  An array is a data structure that stores a collection of values of the same type. You access each individual value through an integer index. If a is an array of integers, then a[i] is the ith integer in the array. You can define an array variable either as int[] a; or as int a[]; To find the number of elements of an array, use array.length. When you create an array of numbers, all elements are initialized with zero. Arrays of boolean are initialized with false. Arrays of objects are initialized with the special value null.

61.  Java SE 5.0 introduced a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values. The enhanced for loop:

for (variable : collection) statement; 

sets the given variable to each element of the collection and then executes the statement. The collection expression must be an array or an object of a class that implements the Iterable interface.


62.  There is an even easier way to print all values of an array, using the toString method of the Arrays class. The call Arrays.toString(a) returns a string containing the array elements, enclosed in brackets and separated by commas, such as "[2, 3, 5, 7, 11, 13]".

63.  Java has a shorthand to create an array object and supply initial values at the same time:

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 }; 

You can even initialize an anonymous array:

new int[] { 17, 19, 23, 29, 31, 37 } 


64.  If you actually want to copy all values of one array into a new array, you use the copyOf method in the Arrays class:

int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length); 

The second parameter is the length of the new array. If the new array is longer than the original one, the additional elements are filled with 0 if the array contains numbers, false if the array contains boolean values.


65.  To sort an array of numbers, you can use one of the sort methods in the Arrays class. This method uses a tuned version of the QuickSort algorithm that is claimed to be very efficient on most data sets.

66.  Multidimensional arrays use more than one index to access array elements. They are used for tables and other more complex arrangements. You cannot use the array until you initialize it with a call to new:

double[][] balances = new double[NYEARS][NRATES]; 

You can also use a shorthand notion for initializing multidimensional arrays without needing a call to new:

int[][] magicSquare = 

{ 

{16, 3, 2, 13}, 

{5, 10, 11, 8}, 

{9, 6, 7, 12}, 

{4, 15, 14, 1} 

};  

Once the array is initialized, you can access individual elements by supplying two brackets, for example, balances[i][j] .

67.  A “for each” loop does not automatically loop through all entries in a two-dimensional array. Instead, it loops through the rows, which are themselves one-dimensional arrays.

68.  To print out a quick and dirty list of the elements of a two-dimensional array, call System.out.println(Arrays.deepToString(a)); The output is formatted like this:
[[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]].

69.  Java has no multidimensional arrays at all, only one-dimensional arrays. Multidimensional arrays are faked as “arrays of arrays.” It is easy to make “ ragged ” arrays, that is, arrays in which different rows have different lengths.

70.  Every Java program has a main method with a String[] args parameter. This parameter indicates that the main method receives an array of strings—namely, the arguments specified on the command line. The name of the program is not stored in the args array.