`
leonzhx
  • 浏览: 793344 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Chapter 3. Fundamental programming structures in Java -- Core Java Ninth Edition

阅读更多

1.  Java is case sensitive.

 

2.  The rules for class names in Java are quite generous. Names must begin with a letter, 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 0x1.0p-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 ( p ).

 

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 ] .

 

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.  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.

 

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

 

18.  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.

 

19.  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.

 

20.  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.

 

21.  >>> 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.

 

22.  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 ” .)

 

23.  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.




 
  

24.  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.

 

25.  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.

 

26.  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

 

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

 

28.  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.

 

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

 

30.  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.

 

31.  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.

 

32.  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); 
 

 

33.  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--;

 

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

 

35.  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.

 

36.  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.

 

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

 

38.  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.

 

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



 

40.  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.

 

41.  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:


 

42.  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.

 
43.  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.

 

44.  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);

 

45.  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"));

 

 

46.  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"); 

 

47.  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.

 

48.  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 .

 

49.  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.

 

50.  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 .

 

 

51.  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.

 

 

52.   

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.

 

 

53.  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.

 

 

54.   

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. 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.

 

55.  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.

 

56.  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.

 

57.  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) 
 

58.  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 i th 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.

 

59.  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.

 

 

60.  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]".

 

61.  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 }
 

 

62.  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.

 

 

63.  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.

 

64.  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] .

 

65.  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.

 

66.  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]].

 

67.  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.

  • 大小: 49.8 KB
  • 大小: 61.7 KB
  • 大小: 144.9 KB
  • 大小: 135.4 KB
  • 大小: 112.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics