学习《core java》记录 -- 第三章

来源:互联网 发布:淘宝商城2016女装新款 编辑:程序博客网 时间:2024/05/21 04:20

学习《core java》记录 – 第三章

摘自《Java核心技术》(第8版)(评注版) Cay S. Horstmann, Gary Cornell, 公飞

Data Types

Integer Types

Type Storage Requirement int 4 bytes short 2 bytes long 8 bytes byte 1 byte

Floating-Point Types

Type Storage Requirement float 4 bytes double 8 bytes

Numbers of type float have a suffix F (3.14F). Floating-point numbers without an F suffix (3.14) are always considered to be of type double. You can optional supply the D suffix (3.14D).
There are 3 special floating-point values to denote overflows and errors:

  • Positive infinity
  • Negative infinity
  • NaN (Not a number)

For example, the result of dividing a positive number by 0 is positive infinity. Computing 0/0 or the square root of a negative number yields NaN.

if (x == Double.Nan) // is never true, can not be used
if (Double.isNan(x)) // check whether x is "not a number"

The char Type

Unicode code units can be expressed as hexadecimal values that run from \u0000 to \uFFFF.
Escape Sequences for Special Characters

Escape Sequence Name Unicode Value \b Backspace \u0008 \t Tab \u0009 \n Linefeed \u000a \r Carriage return \u000d \” Double quote \u0022 \’ Single quote \u0027 \\ Backslash \u005c

We need a bit of terminology to explain how this problem (the 16-bit char type is insufficiant to describe all Unicode characters) is resolved in Java, beginning with Java SE 5.0. A code point is a code value that is associated with a character in an encoding scheme. In the Unicode standard, code points are written in hexadecimal and prefixed with U+, such as U+0063 for the code point of the letter a. Unicode has code points that are grouped into 17 code planes. The first code plane, called the basic multilingual plane, consists of the “classic” Unicode characters with code points U+0000 to U+FFFF. 16 addtional planes, with code points U+10000 to U+10FFFF, hold the supplimentary characters.
The UTF-16 encoding is a method (there are other methods too, like UTF-8、UTF-32)of representing all Unicode code points in a variable-length code. The characters in the basic multilingual plane are represented as 16-bit values, called code units. The supplimentary characters are encoded as consecutive pairs of code units. Each of the values in such an encoding pair falls into a range of 2048 unused values of the basic multilingual plane, called the surrogates area (U+D800 to U+DBFF for the first code unit, U+DC00 to U+DFFF for the second code unit). You can immediately tell whether a code unit encodes a single character or whether it is the first or second part of a supplementary character. 可以参考百度百科 Unicode
code-point与编码方案有关(Unicode)
code-unit与编码方案的具体实现方式有关(UTF-16是Unicode的一种编码方式)
两者是在不同的域里面的术语。
In java, the char type describes a code unit in the UTF-16 encoding.
Stongly recommended that not to use the char type in your programs unless you are actually manipulating UTF-16 code units.

The boolean Type

The boolean type has 2 values, false and true. It is used for evaluating logical conditions. You cannot convert between integers and boolean values.

Variables

Constants

use the keyword final to denote a constant

class constant

the keywords static final for class constant

Operators

usual arithmetic operators \

(+ - * /)
Note that integer division by 0 raise an exception, whereas floating-point division by 0 yields an infinite ro NaN result.
The Java programming language was updated to recognize the conflicting demands for optimum performance and perfect reproducibilty. By default, virtual machine designers are now permitted to use extended precision for intermediat 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.
不使用strictfp关键字的默认情况下工作正常的程序,若改为使用strictfp,就有可能发生溢出。

Increment and Decrement Operators

(++, –)

Relational and boolean Operators

(==, !=, <, >, <=, >=, &&, ||, condition ? expression1 : expression2)

Bitwise Operators

(&, |, ^, ~, >>, <<, >>>)
a >>> operator fills the top bits with zero, whereas >> extents the sign bit into the top bits. There is no <<< operator.

Mathematical Functions and Constants

the Math class
the Strict Math class

Conversions between Numeric Types

When 2 values with a binary operator 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.

Casts

The syntax for casting is to give the target type in parentheses, followed by the variable name.
(target-type) variable;

Parentheses and Operator Hierarchy

Enumerated Types

enum Size { S, M, L, XL};

Strings

the String class

Strings are immutable

The String class gives no methods that let you change a character in an existing string.
对于多次变化的字符串处理,出于性能的考虑,建议使用StringBuffer来处理。

Code Points and Code Units

// the number of code unitsString::length();  // the number of code pointString::codePointCount(int beginIndex, int endIndex);  

Reading the On-Line API Documentation

Point your web browser to the docs/api/index.html subdirectory of your JDK installation.

Building Strings

the StringBuilder Class
If all string editing happens in a single thread, you should use StringBuilder.
the StringBuffer Class
StringBuffer is slightly less efficient, but it allows multiple threads to add or remove character.

Input and Output

Reading Input

the Scanner class – java.util.Scanner
To read console input, you first construct a Scanner that is attached to System.in.
The Scanner class is defined in the java.util package.
Scanner in = new Scanner(System.in);
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.
java.io.Consol

Console cons = System.console();Strng 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.

Formatting Output

System.out.printf()String.format()

File Input and Output

Scanner in = new Scanner(new File("c:\\mydirectory\\myfile.txt"));// Java SE 7Scanner in = new Scanner(Paths.get("c:\\mydirectory\\myfile.txt"));PrintWriter out = new PrintWriter(new File("c:\\mydirectory\\myfile.txt"));PrintWriter out = new PrintWriter("c:\\mydirectory\\myfile.txt");

You can get the directory location with this call:
String dir = System.getProperty("user.dir");

Whne you launch a program from a command shell, you can use the redirection sytax of your shell and attach any file to System.in and System.out:
java MyProg < input.txt > output.txt

Control Flow

Block Scope

在内嵌的程序块内部不能定义与外部作用域中同名的变量名。

Conditional Statement

if (condition) statementif (condition) statement1 else statment2if (condition) { statement1 }else if (condition) { statement2 }else { statement3 }

An else groups with the closest if.
建议总是使用{}明确标明ifelse的范围,以提高程序的可读性和可维护性。

Loops

while (condition) statementdo statement while (condition);

Determinate Loops

the for loop
for (initialize; test; update)
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. If you define a variable inside a for statement, you cannot use the value of that variable outside the loop.

Multiple Selections – The swich Statement

In the case labels must be integers or enumerated constants. You cannot test strings.(过时的)
A case label can be:

  • char, byte, short, int(或者是Character, Byte, Short, Integer)类型的常量表达式
  • 枚举常量(enumerated constants)
  • 从Java SE 7开始,字符串常量也可以( case “yes”: )

Statements That Break Control Flow

break statement

break;break label;  // labeled break

Notice that the label must precede the outermost loop out of which you want to break. It also must be followed by a colon(:). The labeled break moves past the end of the labeled blocks.
You can apply a label to any statement, even an if statement or a block statement.

label:{    ...    if (condition) break label;  // exits blocks    ...}// jumps here when the break statement executes

continue statement

continue;continue label;

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.

Big Numbers

java.math package
the BigIntger class
the BigDecimal class

Arrays

The “for each” Loop

“只读式”的遍历
The enhanced for loop
for (variable : collection) statement
sets the given variable to each element of the collection and then executes the statement/block. The collection expression must be an array or an object of a class that implements the Iterable interface.

Array Initializers and Anonymous Arrays

Java has a shorthand to create an array object and supply initial values at the same time.
int[] smallPrimes = { 2, 3, 4 };
Notice that you do not call new when you use this syntax.
anonymous array
new int[] { 17, 18, 19 };
you can use this syntax to reinitialize an array without creating a new variable.

// shorthand for // int[] anonymous = { 17, 18, 19 };// smallPrimes = anonymous;smallPrimes = new int[] { 17, 18, 19 };

It is legal to have arrays of length 0. Such an array can be useful if you write a method that computes an array result and the happens to be empty.(????) You construct an array of length 0 as
new elementType[0]
Note that an array of lengh 0 is not the same as null.

Array Copying

You can copy one array variable into another, but then both variables refer to the same array:
int[] newArray = oldArray;
Actually copy all values of one array into a new array, use copyOf method in the Arrays class or arraycopy method in the System class.
Arrays.copyOf()
System.arraycopy()

Array Sorting

Arrays.sort() // QuickSort algorithm

Multidimensional Arrays

int[][] matrix;

for (int[] row : a)    for (int value : row)        //do sth. with value

Ragged Arrays

Java has no multidimensional arrays at all, only one-dimensional arrays. Multidimensional arrays are faked as “arrays of arrays”.

0 0
原创粉丝点击